I would like to declare an array, temporally change it's value while storing the old value, perform some computation and then later restore the original array value. Of this process, my original array declaration, reassigning the array, and even the temporary array copy seem to all be working. However I am running into an issue with the final restoration of the array back to its original value.
The below script demonstrates the issue. MY_ARR is the main array and SAVE_MY_ARR is the copy I am making while I modify the array temporarily before restoring it. As per the script comments, everything prints out as expected, with the exception of the original array after restoring its value. What am I doing incorrectly here?
The script:
IFS=$'\n'
MY_ARR=(one two three)
# GOOD: prints "one,two,three,"
for i in ${MY_ARR[@]}; do
echo -n "$i,"
done
echo ""
SAVE_MY_ARR=("${MY_ARR[@]}")
MY_ARR=(foo)
# GOOD: prints "foo,"
for i in ${MY_ARR[@]}; do
echo -n "$i,"
done
echo ""
# GOOD: prints "one;two;three"
for i in ${SAVE_MY_ARR[@]}; do
echo -n "$i;"
done
echo ""
# BAD: prints "one," and not "one,two,three,"
MY_ARR=("${SAVE_MY_ARR}")
for i in ${MY_ARR[@]}; do
echo -n "$i,"
done
echo ""
The output:
one,two,three,
foo,
one;two;three;
one,