Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash - How to declare a local integer?

Tags:

bash

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.

like image 933
helpermethod Avatar asked Jun 25 '12 10:06

helpermethod


People also ask

How do you assign an integer in bash?

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.

How do I declare a variable in bash?

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.

How do you declare a local variable in Linux?

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.


1 Answers

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
like image 156
Dennis Williamson Avatar answered Sep 23 '22 12:09

Dennis Williamson