Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concatenate arrays using iteration in name with bash

I would like to concatenate unlimited numbers of arrays using shortest lines possible, so for this I did the code below:

#!/bin/bash
declare -a list1=("element1")
declare -a list2=("element2")
declare -a list3=("element3")
declare -a list4=("element4")
declare -a list
for i in {1..4}
do
   list=( ${list[@]} ${list$i[@]} )
done
echo ${list[*]}

But the code above is not working because $i is not seen as variable and the error is: ${list$i[@]} bad substitution

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The following code outputs all 4 lists concatenated together.

eval echo \${list{1..4}[*]}

This code runs filename expansion over the result of list elements (* is replaced by filenames). Consider sacrificing 4 characters and doing \"\${list{1..4}[*]}\".

Note that eval is evil https://mywiki.wooledge.org/BashFAQ/048 and such code is confusing. I wouldn’t write such code in a real script – I would definitely use a loop. Use shellcheck to check your scripts.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading