I have written a hand full of Bash scripts, but none of those utilized array. Why? It’s because of two main things: 1. I don’t know how to use array in Bash, and 2. I would normally switch to write the script in Python instead.

Today, however, I need to update an existing script written in Bash to make use of array. This was a perfect excuse for me to spend some 30 minutes to learn about array in Bash. I found a very good tutorial at the following [1].

Here’s my script which doesn’t really do anything beside demonstrating how to use array in Bash.

sitePath="/var/www/site1"
targetDirs=("conf" "data/attic" "data/media" "data/meta" "data/pages")

printf "Interate through each item in an array:\n\n"

for dir in ${targetDirs[@]}; do
    echo ${sitePath}/${dir}
done

printf "\nFlatten an array with space separated, and assigned the output to a variable called 'newVar'\n\n"
printf -v newVar "${sitePath}/%s " "${targetDirs[@]}"

printf "newVar: %s\n\n" "${newVar}"

And here is the sample output when run:

Interate through each item in an array:

/var/www/site1/conf
/var/www/site1/data/attic
/var/www/site1/data/media
/var/www/site1/data/meta
/var/www/site1/data/pages

Flatten an array with space separated, and assigned the output to a variable called 'newVar'

newVar: /var/www/site1/conf /var/www/site1/data/attic /var/www/site1/data/media /var/www/site1/data/meta /var/www/site1/data/pages

Array in Bash seems to be pretty straightforward. As mentioned, a very good explanation about Bash array is available at the reference [1] below.

Reference: