0

If I iterate in bash over multiple arrays and printing its values then the values of the arrays changes. Why?

#!/bin/bash

a=("02" "20")
b=("02" "20")
n=("02" "20")
p=("02" "20")

for p in ${p[@]}
do
    for b in ${b[@]} 
    do
        for a in ${a[@]} 
        do 
           for n in ${n[@]} 
           do
             echo $b-$a-$n-$p
           done;
        done;
    done;
done
echo "${a[*]}"

The command echo "${a[*]}" yields 20 20 but should be 02 20

Thanks!

1
  • You could have demonstrated this with a single array: for a in ${a[@]}; do :; done. In the future, please try to debug your problems yourself. Commented Apr 23, 2021 at 18:51

1 Answer 1

3

This line:

    for a in ${a[@]} 

is reassigning the value of a (which in this case means reassigning the zeroth index of a).

1
  • Yup. But it's only ${a[0]} that is affected/changed since a is the same as ${a[0]} if a is an array.
    – Kusalananda
    Commented Apr 23, 2021 at 17:53

You must log in to answer this question.

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