Using Arrays in Bash

Using Arrays in Bash

In bash you can use arrays. Lets see some examples.

Create new array:

ARR=("a" "b" "c")

Show all array values:

[root@knesenko-centos7 ~]# echo "${ARR[@]}"
a b c
[root@knesenko-centos7 ~]# echo "${ARR[*]}"
a b c
[root@knesenko-centos7 ~]#

Difference between ‘*’ and ‘@’. Same as in positional parameters:

[root@knesenko-centos7 ~]# cat "${ARR[@]}"
cat: : No such file or directory
cat: b: No such file or directory
cat: c: No such file or directory
cat: c: No such file or directory
[root@knesenko-centos7 ~]# cat "${ARR[*]}"
cat:  b c c: No such file or directory
[root@knesenko-centos7 ~]#

Loop over all array elements:

for i in "${ARR[@]}"; do
    echo "${i}"
done

Show how many values are in array:

[root@knesenko-centos7 ~]# echo "${#ARR[@]}"
3

Access specific value:

[root@knesenko-centos7 ~]# echo "${ARR[1]}"
b

Add value to array:

ARR+=("d")
[root@knesenko-centos7 ~]# echo "${ARR[@]}"
a b c d

Remove a value from array:

[root@knesenko-centos7 ~]# echo "${ARR[@]/a}"
 b c c
[root@knesenko-centos7 ~]# ARR=("${ARR[@]/a}")
[root@knesenko-centos7 ~]# echo "${ARR[@]}"
 b c c
[root@knesenko-centos7 ~]#