Example: Bash Arrays

ref

Declare Array and Assigning Values

arr[index]=value
arr[0]='a'
arr[1]='b'
echo ${arr[1]}
## b
## b

Initializing during declaration

Two options:

declare -a arr=(el1 el2)
arr=(el1 el2)
arr=('a' 'b')
echo ${arr[1]}
## b
## b

Read a File into an Array

arr=(`cat ./data/bash_sample_csv.csv`)
echo ${arr[@]}
## col1,col2 row11,row12 row21,row22
## col1,col2 row11,row12 row21,row22

Loop over array

arr=('a' 'b')
for el in "${arr[@]}"; do 
  echo $el
done
## a
## b
## a
## b

Loop over a space separated string

str="a b"
for el in $str; do 
  echo $el
done
## a 
## b
## a
## b

 Tech    14 Dec, 2017

Any work (images, writings, presentations, ideas or whatever) which I own is always provided under
Creative Commons License Creative Commons Attribution-Share Alike 3.0 License

Mert Nuhoglu is a Trabzon-born programmer and data scientist.

You may also like...