2

Suppose I declare an array Unix

declare -a Unix=('Debian' 'Red hat' 'Suse' 'Fedora')

I can append to the array as such

Unix=("${Unix[@]}" "AIX")

I introduce another variable a which points to a string naming the earlier Unix variable

a=Unix

Can I append to the array through this second variable? The reason I want to know is I'm trying to write a function which takes a variable that 'points to an array'.

2 Answers 2

6

Use the declare builtin. Its argument undergoes expansion before the assignment is performed, so that $a is expanded to the name of the array to update before the assignment takes place.

declare "$a+=( Aix )"
Sign up to request clarification or add additional context in comments.

Comments

1

Escape everything so that only a is substituted and all else remains as is, then use eval -

Unix=('Debian' 'Red hat' 'Suse' 'Fedora')
a=Unix
eval "$a=( \"\${$a[@]}\" \"AIX\" )"

1 Comment

Unnecessary use of eval: declare "$a+=( AIX )".

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.