Merging two arrays in Bash
Since Bash supports sparse arrays, it's better to iterate over the array than to use an index based on the size.
a=(0 1); b=(2 3)
i=0
for z in ${a[@]}
do
for y in ${b[@]}
do
c[i++]="$z:$y"
done
done
declare -p c # dump the array
Outputs:
declare -a c='([0]="0:2" [1]="0:3" [2]="1:2" [3]="1:3")'
If you don't care about having duplicates, or maintaining indexes, then you can concatenate the two arrays in one line with:
NEW=("${OLD1[@]}" "${OLD2[@]}")
Full example:
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');
UnixShell=("${Unix[@]}" "${Shell[@]}")
echo ${UnixShell[@]}
echo ${#UnixShell[@]}
Credit: http://www.thegeekstuff.com/2010/06/bash-array-tutorial/