Working with Arrays in Bash



It almost looks like a regular variable, but you add parentheses to it. And items are separated by spaces (or newlines), not commas.

movies=( "The Holy Grail" "The Life of Brian" "The Meaning of Life" )


Ever wondered how you print an array in bash? It's not like this, this only prints the first element.

echo $movies


You use the @ symbol to print all the elements.

echo ${movies[@]} # the "@" sign refers to all the elements.


Ever wondered how you print the length of an array in bash? The # symbol is used to print the length of an array. So you would think that this would print the length of the array:

echo ${#movies} # this prints the length of the first element. echo ${#movies[0]} # does the same thing here.


Nope. This prints the length of the array.

echo ${#movies[@]} # because the "@" references all the elements.


Ever wondered how you get a random element?

echo ${movies[$RANDOM % ${#movies[@]}]}


RANDOM is a special variable that returns a random integer between 0 and 32767. The modulo operator (%) is used to get a random number between 0 and the length of the array.



Thank you for coming to my TEDTalk.


Authored by Anthony Fox on 2023-09-21