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?

0

1 Answer 1

6

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .