Example: Bash Arrays
My study notes and examples to remember how to use bash arrays.
Table of Contents
ref:
- http://www.tldp.org/LDP/abs/html/arrays.html
- http://www.thegeekstuff.com/2010/06/bash-array-tutorial
- http://www.yourownlinux.com/2016/12/bash-scripting-arrays-examples.html
Declare Array and Assigning Values
arr[index]=value
arr[0]='a'
arr[1]='b'
echo ${arr[1]}
## b
Initializing during declaration
Two options:
declare -a arr=(el1 el2)
arr=(el1 el2)
arr=('a' 'b')
echo ${arr[1]}
## b
Print all elements
echo ${arr[@]}
## a b
Read a File into an Array
arr=(`cat ./data/bash_sample_csv.csv`)
echo ${arr[@]}
## col1,col2 row11,row12 row21,row22
Loop over array
arr=('a' 'b')
for el in "${arr[@]}"; do
echo $el
done
## a
## b
Loop over a space separated string
str="a b"
for el in $str; do
echo $el
done
## a
## b