1

I need to iterate on an array and expand the array while iterating. How do I do it in BASH?

For example:

req="a b c d"
read -a MODULES <<<$req

for MODULE_NAME in "${MODULES[@]}"; do
    echo $MODULE_NAME
    if something-happens-only-one-time; then 
        MODULES+=( "e" )
    fi
done

I want to get the following output:

a
b
c
d
e

Edit:

Following code works for now:

i=0
while true; do
    MODULE_NAME="${MODULES[$i]}"
    echo ${MODULE_NAME}

    if something-happens-only-one-time; then 
        MODULES+=( "e" )
    fi

    i=$((i+1))
    num_of_modules=${#MODULES[@]}
    if (("$i" >= "$num_of_modules")) ; then 
        break
    fi
done 
1
1

It doesn't work with a for ... in "${arr[@]}" loop because "${arr[@]}" is evaluated immediately. That is, even though you add elements to it during the loop, the range of the loop is already determined, and won't be affected.

You could rewrite as a counting for loop:

for ((i = 0; i < "${#MODULES[@]}"; i++)); do
    MODULE_NAME=${MODULES[$i]}
    echo $MODULE_NAME
    if something-happens-only-one-time; then 
        MODULES+=( "e" )
    fi
done

This works because ${#MODULES[@]} in the loop condition is re-evaluated in every loop cycle. So after a value is appended during the loop, then at the start of the next cycle the value of ${#MODULES[@]} will be increased by 1.

2

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.