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 に答える