1

With the following code I can copy an array content to another one so that when altering one array the other is untouched.

#!/bin/bash
declare -a ARRAY_A=(a b c d e)
ARRAY_B=("${ARRAY_A[@]}")

echo "Before removal:"

printf "%s " ${ARRAY_A[@]}
echo
printf "%s " ${ARRAY_B[@]}
echo

echo
echo "After removal:"
unset ARRAY_A[0]

printf "%s " ${ARRAY_A[@]}
echo
printf "%s " ${ARRAY_B[@]}
echo

Prints:

Before removal:
a b c d e 
a b c d e 

After removal:
b c d e 
a b c d e

Is it possible to copy the reference to that array instead, so that when altering one array the "other" (which is the same then) appears to be changed as well (like below)?

Before removal:
a b c d e 
a b c d e 

After removal:
b c d e 
b c d e

1 Answer 1

5

Yes? Just use a bash name reference.

#!/bin/bash
declare -a ARRAY_A=(a b c d e)
declare -n ARRAY_B=ARRAY_A

echo "Before removal:"

printf "%s " "${ARRAY_A[@]}"
echo
printf "%s " "${ARRAY_B[@]}"
echo

echo
echo "After removal:"
unset ARRAY_A[0]

printf "%s " "${ARRAY_A[@]}"
echo
printf "%s " "${ARRAY_B[@]}"
echo

Note: prefer to use lowercase variables in your scripts. Upper case variables are by convention meant to be exported variables, like COLUMN, LINES, PWD, UID, IFS, etc.

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.