MOHAMED MOHAMED - 1 year ago 89
Bash Question

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

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?

Answer Source

With bash you cannot really get that (I imagine you want some variable shared between several instances of your shell...). However, if you switch to the fish shell (use chsh to change your login shell), you get so called universal variables which kind-of fits the bill. See also this answer to a related question.

BTW, you should read advanced bash scripting guide and consider using bash functions (instead of a script).

If you just want to share a variable between several shell functions inside the same shell process, just don't declare it local to functions!