14

在 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
}

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

4

3 回答 3

24

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"

输出是:

Before the function, $number has the value 10
In func, $number has the value 20
After the function, $number has the value 10
于 2012-06-25T11:15:51.283 回答
18

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

local [option] name[=value] ...

对于每个参数,都会创建一个名为 name 的局部变量,并为其赋值。该选项可以是 declare 接受的任何选项。

所以local -i是有效的。

于 2012-06-25T10:34:27.923 回答
1

如果您最终在这里使用 Android shell 脚本,您可能想知道 Android 使用的是 MKSH 而不是完整的 Bash,它有一些影响。看一下这个:

#!/system/bin/sh
echo "KSH_VERSION:  $KSH_VERSION"

local -i aa=1
typeset -i bb=1
declare -i cc=1

aa=aa+1;
bb=bb+1;
cc=cc+1;

echo "No fun:"
echo "  local   aa=$aa"
echo "  typset  bb=$bb"
echo "  declare cc=$cc"

myfun() {
    local -i aaf=1
    typeset -i bbf=1
    declare -i ccf=1

    aaf=aaf+1;
    bbf=bbf+1;
    ccf=ccf+1;

    echo "With fun:"  
    echo "  local   aaf=$aaf"
    echo "  typset  bbf=$bbf"
    echo "  declare ccf=$ccf"
}
myfun;

运行这个,我们得到:

# woot.sh
KSH_VERSION:  @(#)MIRBSD KSH R50 2015/04/19
/system/xbin/woot.sh[6]: declare: not found
No fun:
  local   aa=2
  typset  bb=2
  declare cc=cc+1
/system/xbin/woot.sh[31]: declare: not found
With fun:
  local   aaf=2
  typset  bbf=2
  declare ccf=ccf+1

因此在Android declare中不存在。但是读起来,其他的应该是等价的。

于 2017-04-12T23:54:25.257 回答