Is it possible to define a variable as static in shell bash function like C?

Viewed 14006

In C, I can define a static variable in a function like this

int func() {
    static int var=0
    .....
}

Is there something equivalent to that in shell bash linux?

Is it possible to define a local variable of the bash shell function as static?

5 Answers

If you want the static variable to be used within a bash function and to have the life of the bash script you can define and initialize it before the function, making it global, and then use it, without initialization, within the function. The value will have the life of the script.

#!/bin/bash

variable=0

increment()
{
    (( variable++ ))
    echo $variable
}

while true; do
    increment
    sleep 1
done

This will output an incrementing number.

Related