How to use bash array?

bash array shell multiline line

Bash shell has syntax for arrays, values should be separated by space and wrapped with round brackets:59a94420fa767fcd0e133132

Defining array in bash:

dirs=('etc' 'www')

Often arrays tend to be large, so multiline definitions are preferred. It is possible in bash to define array spanning multiple lines by just splitting lines between elements:

dirs=('upload'
'components'
'mail')

As whitespace is ignored in array definition, it can be nicely formatted so that each element can be easily commented:

dirs=(
    'upload'
    'components'
    'mail'
)

Using array in bash loop:

To loop thru array elements in for loop we use asterisk character @ to get all elements:
for dir in "${dirs[@]}"
do
echo "$dir"
done

Above example will display etc and www splitted by new lines. Note, that quoting and [@] syntax ensures, that it will iterate properly also if array element contains spaces.

Adding element to array

dirs+=("new")

Creating empty array

dirs=()