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?
The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.
A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.
What is a Static Variable? In programming, a static variable is the one allocated “statically,” which means its lifetime is throughout the program run. It is declared with the 'static' keyword and persists its value across the function calls.
When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With