Bash Shell Scripting: Arrays

This is a quick overview on how to deal with arrays, including an iteration example. Arrays are bash specific, so good old shell will yield syntax errors.

Initialising Arrays

Suppose you want to organise your favourite turtle names in an array. You should go like this:

$ TMNT=( Leonardo Michelangelo Donatello Raphael )

This creates a four element array. That simple.

Accessing Array Elements

To access an array element, you’ll want to use the curly brace notation:

$ echo ${TMNT[3]}

Raphael

Note that array indexing in Bash Shell is zero-based. You can also print all elements at once like so:

$ echo ${TMNT[*]}

Leonardo Michelangelo Donatello Raphael

Array Length

With curly braces and a “#”, you’ll get the array length with this simple notation:

$ echo ${#TMNT[*]}

4

It’s the “print everything” with that hash preceding the array name.

Array Iteration

For the most common scenario, you’ll get away with this:

$ for TURTLE in ${TMNT[*]}

> do

> echo $TURTLE

> done

Leonardo

Michelangelo

Donatello

Raphael

For bigger arrays you’ll want to use proper indexing:

I=0

while [ $I -lt ${#TMNT[*]} ]

do

echo ${TMNT[$I]}

I=$((I+1))

done

Leonardo

Michelangelo

Donatello

Raphael

And that’s it for today.


If you have any questions, feel free to ask in the comments section. Also, if this helped you in any way, please like and share. Until next time!

Leave a comment