Software >> OS >> Unix >> Shell >> bash >> Array manipulation examples

 Summary
 

Syntax Result
arr=() Create an empty array
arr=(1 2 3) Initialize array
${arr[2]} Retrieve third element
${arr[@]} Retrieve all elements
${!arr[@]} Retrieve array indices
${#arr[@]} Calculate array size
arr[0]=3 Overwrite 1st element
arr+=(4) Append value(s)
str=$(ls) Save ls output as a string
arr=( $(ls) ) Save ls output as an array of files
${arr[@]:s:n} Retrieve n elements starting at index s

 

S/N Action Example(s)
1 Declare

# indexed array

declare -a myarray1

declare -a myarray2=()

declare -a myarray3=(abc def ghi)

declare -a myarray4=('abc' 'def' 'ghi')

# Associative array

declare -A myhash

declare -A myhash=([1]="string1" [2]="string2" [4]="string4")

2 Display

declare -a myarray=(a b c d e f g h i j k)

# DISPLAY ALL ELEMENTS OF AN ARRAY

echo ${myarray[@]}

a b c d e f g h i j k

 

# DISPLAY SPECIFIC LEMENTS OF AN ARRAY E.G. INDEX 0

echo ${myarray[0]}

a

 

# DISPLAY SPECIFIC ELEMENTS OF 2 DIMENTION ARRAY E.G. INDEX 0,0

echo ${matrix[0,0]}

 

# DISPLAY A RANGE OF ELEMENTS STARTING AT INDEX 1 ENDING AT 3

echo ${myarray[@]:1:3}

b c d

# Fetching values from associative arrays 
echo ${arr[my key]}
echo ${arr["my key"]}
echo ${arr[$my_key]}
3 Assign

# assign one element in indexed array

declare -a myarray
myarray[0]=A

# Assigning values to associative arrays 
arr[my key]="my value"
arr["my key"]="my value"
arr[$my_key]="my value"
 4 Count

# GET THE LENGTH OF THE ARRAY

echo ${#myarray[@]}

# COUNT CHARACTERS IN ONE ELEMENT OF THE ARRAY

echo ${#myarray[0]}

 5 Iterate

# INDEXED ARRAY - iterate by the elements
declare -a myarray=(a b c d)
for e in "${myarray[@]}"
do
   echo $e
done

# INDEXED ARRAY - iterate by the indices
declare -a myarray=(a b c d)
for ((i=0;i<${#myarray[@]};i++));
do
   printf "%d : %s\n" $i ${myarray[$i]};
done;
 

# ASSOCIATIVE ARRAY
for k in "${!array[@]}"
do
printf "%s\n" "$k=${array[$k]}"
done

 

  Copy # COPY AN ARRAY TO ANOTHER VARIABLE
declare -a original=("a" "b" "c" "d")
copy=(${original[*]})

for e in "${original[@]}";do echo $e;done;
a
b
c
d

for e in "${copy[@]}";do echo $e;done;
a
b
c
d
     
     
     

 References:: https://www.thegeekstuff.com/2010/06/bash-array-tutorial/