带参数的循环函数在另一个带参数的循环函数中

6eq*_*uj5 1 scripting bash function arguments

# Print $1 $2 times
function foo() {
    for (( i=0; i<$2; i++ )); do
        echo -n $1
    done
    echo
}

# Print $1 $2x$3 times
function bar() {
    for (( i=0; i<$3; i++ )); do
        foo $1 $2
    done
}

bar $1 $2 $3
Run Code Online (Sandbox Code Playgroud)

的理想输出foobar.sh @ 3 3

@@@
@@@
@@@
Run Code Online (Sandbox Code Playgroud)

但实际输出似乎只是

@@@
Run Code Online (Sandbox Code Playgroud)

将变量更改为bar()fromij产生所需的输出。但为什么?

mar*_*raf 5

因为变量在 shell 脚本中是“全局的”,除非你将它们声明为本地的。因此,如果一个函数更改了您的变量i,另一个函数将看到这些更改并做出相应的行为。

因此,对于函数中使用的变量——尤其是像 i、j、x、y 这样的循环变量——必须将它们声明为局部变量。见下文...

#!/bin/bash
# Print $1 $2 times
function foo() {
  local i
  for (( i=0; i<"$2"; i++ )); do
    echo -n $1
  done
  echo
}

# Print $1 $2x$3 times
function bar() {
  local i
  for (( i=0; i<"$3"; i++ )); do
    foo "$1" "$2"
  done
}

bar "$1" "$2" "$3"
Run Code Online (Sandbox Code Playgroud)

结果:

$ ./foobar.sh a 3 3
aaa
aaa
aaa
$ ./foobar.sh 'a b ' 4 3
a ba ba ba b
a ba ba ba b
a ba ba ba b

Run Code Online (Sandbox Code Playgroud)