Edit: This has been flagged as a duplicate so let me explain how this is unique: 1. This uses for loops 2. This should be portable across all versions of bash
first_array=(1 2 3)
second_array=(4 5 6)
do_stuff () {
_array1=( "$1" )
_array2=( "$2" )
for i in "${_array1[@]}"; do
for i in "${_array2[@]}"; do
echo "$i"
done
done
}
do_stuff "$(echo ${first_array[@]})" "$(echo ${second_array[@]})"
This outputs:
4 5 6
Instead of:
4
5
6
4
5
6
4
5
6
Why? It works fine if I don't pass arrays as parameters, such as:
_array1=(1 2 3)
_array2=(4 5 6)
do_stuff () {
for i in "${_array1[@]}"; do
for i in "${_array2[@]}"; do
echo "$i"
done
done
}
do_stuff
Produces this output:
4
5
6
4
5
6
4
5
6
I would like to be able to get this result but passing different arrays of my choosing in order to avoid rewriting similar functions.