Home > OS >  Concatenate arrays using iteration in name with bash
Concatenate arrays using iteration in name with bash

Time:01-18

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

CodePudding user response:

You can use variable indirection:

for i in {1..4} ; do
    ref="list$i[@]"
    list =(${!ref})
done
echo "${list[@]}"

CodePudding user response:

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.

  •  Tags:  
  • Related