1
# 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

The ideal output of foobar.sh @ 3 3 is

@@@
@@@
@@@

but the actual output seems to be just

@@@

Changing the variable in bar() from i to j yields the desired output. But why?

5

Because variables are "global" in shell-scripts, unless you declare them as local. So if one function changes your variable i, the other function will see these changes and behave accordingly.

So for variables used in functions --especially loop-variables like i, j, x, y-- declareing them as local is a must. See below...

#!/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"

Result:

$ ./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

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.