bash - 如何声明一个本地整数?

hel*_*hod 10 bash

在Bash中,我如何声明一个局部整数变量,例如:

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
}
Run Code Online (Sandbox Code Playgroud)

在某个地方,我看到local -i number=0被使用,但这看起来不太方便.

eca*_*mur 15

根据http://www.gnu.org/software/bash/manual/bashref.html#Bash-Builtins,

local [option] name[=value] ...
Run Code Online (Sandbox Code Playgroud)

对于每个参数,将创建名为name的局部变量,并为其指定值.该选项可以是声明接受的任何选项.

所以local -i是有效的.


Pau*_*ce. 13

declare函数内部自动使变量本地化.这样可行:

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"
Run Code Online (Sandbox Code Playgroud)

输出是:

Before the function, $number has the value 10
In func, $number has the value 20
After the function, $number has the value 10
Run Code Online (Sandbox Code Playgroud)