Sebastian Barth
Sebastian Barth

Reputation: 4537

Bash copy variable containing array as reference

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

Upvotes: 1

Views: 41

Answers (1)

KamilCuk
KamilCuk

Reputation: 141393

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.

Upvotes: 5

Related Questions