Bash Arrays



Arrays in Bash are quite simple. Here are some array examples to get you going. The official Bash documentation has more details and examples.

Initialize an entire array:

bash$ DAYS=(mon tue wed thu fri sat sun)

There are two ways to reference an entire array:

bash$ echo ${DAYS[@]}
mon tue wed thu fri sat sun
bash$ echo ${DAYS[*]}
mon tue wed thu fri sat sun

Initialize array element

bash$ ARRAY[0]="Fedora"
bash$ ARRAY[1]="RedHat"
bash$ ARRAY[2]="CentOS"

Display an element

bash$ echo ${ARRAY[0]}
Fedora

Get the length of an array:

bash$ echo ${#ARRAY[@]}
3

Get the length of an array value based on index:

bash$ echo ${ARRAY[0]}
Fedora
bash$ echo ${#ARRAY[0]}
6

Get the subset of an array through trailing substring extraction:

bash$ echo ${ARRAY[@]:0}
Fedora RedHat CentOS
bash$ echo ${ARRAY[@]:1}
RedHat CentOS
bash$ echo ${ARRAY[@]:2}
CentOS