This is how we can combine or concatenate arrays in bash scripting.
$ cat combinearr.sh
#!/bin/sh
#Combine or concatenating arrays in Bash
# Source : http://tldp.org/LDP/abs/html/arrays.html
# Subscript packed.
declare -a arrA=( A1 B1 C1 )
echo "____________"
echo "Array arrA"
echo "____________"
for (( i = 0 ; i < 3 ; i++ ))
do
echo "Element [$i]: ${arrA[$i]}"
done
# Subscript sparse ([1] is not defined).
declare -a arrB=( [0]=A2 [2]=C2 [3]=D2 )
echo "____________"
echo "Array arrB"
echo "____________"
for (( i = 0 ; i < 4 ; i++ ))
do
echo "Element [$i]: ${arrB[$i]}"
done
declare -a arrayX
#Combine arrA and arrB
arrayX=( ${arrA[@]} ${arrB[@]} )
echo "____________"
echo "Array arrayX"
echo "____________"
echo "${arrayX[@]}"
cnt=${#arrayX[@]}
echo "____________"
echo "Array arrayX"
echo "____________"
for (( i = 0 ; i < cnt ; i++ ))
do
echo "Element [$i]: ${arrayX[$i]}"
done
Running the script:
$ ./combinearr.sh
____________
Array arrA
____________
Element [0]: A1
Element [1]: B1
Element [2]: C1
____________
Array arrB
____________
Element [0]: A2
Element [1]:
Element [2]: C2
Element [3]: D2
____________
Array arrayX
____________
A1 B1 C1 A2 C2 D2
____________
Array arrayX
____________
Element [0]: A1
Element [1]: B1
Element [2]: C1
Element [3]: A2
Element [4]: C2
Element [5]: D2
More of arrays in Bash can be found here
1 comment:
there might be a simpler way to do it:
combine=( `echo ${array1[@]}` `echo ${array2[@]}` )
Post a Comment