In Bash, how do I declare a local integer variable, i.e. something like:
func() {
local ((number = 0)) # I know this does not work
local declare -i number=0 # this doesn't work either
# other statements, possibly modifying number
}
Somewhere I saw local -i number=0
being used, but this doesn't look very portable.
Bash lets you declare a variable to have the integer attribute, which guarantees that the variable always holds an integer value. It also permits arithmetic evaluation when assigning a value. Declare that myvar should be treated an integer. The above command assigns myvar the value of 2 times 11.
There are no data types. 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.
Local Variables − A local variable is a variable that is present within the current instance of the shell. It is not available to programs that are started by the shell. They are set at the command prompt. Environment Variables − An environment variable is available to any child process of the shell.
declare
inside a function automatically makes the variable local. So this works:
func() {
declare -i number=0
number=20
echo "In ${FUNCNAME[0]}, \$number has the value $number"
}
number=10
echo "Before the function, \$number has the value $number"
func
echo "After the function, \$number has the value $number"
And the output is:
Before the function, $number has the value 10
In func, $number has the value 20
After the function, $number has the value 10
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