1

Nested functions in for loop seems to be not working as expected. The loop breaks after iterating once

# copy files
copyFiles () {
   for (( i=0; i<${#filetype[@]}; ++i )); do
     //some code goes here
   done
}

# copy common components
copyComponents () {
  copyFiles $1
}

for (( i=0; i<3; ++i )); do
  echo $i //iterates only once.. expectation is thrice
  case $1 in
    components)
       copyComponents $module;;
    *)
       echo "unknown type"
   esac
done

I am not sure what I am doing wrong but for loop exits after iterating once.

1 Answer 1

3

The problem is that all variables in shell are global unless declared otherwise. Here's a simpler example that demonstrates this:

func () {
    for ((i=0; i<10; ++i)); do
        echo "func: $i"
    done
}

for ((i=0; i<5; ++i)); do
    echo "Loop: $i"
    func
done

echo "$i"

If you run the, you'll see that after func is executed the first time, the value of the global variable i is 11, which causes the outer loop to exit. To fix this in bash, you can ensure that the loop counter in your function stays local.

copyFiles () {
    local i
    for (( i=0; i<${#filetype[@]}; ++i )); do
        # some code goes here
    done
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.