Working with Arrays in Bash

September 21, 2023 · 1 min read · 248 words · bash, linux



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.

Previous

Python Unveiled

Next

Jellybeans.nvim


Authored by Anthony Fox on September 21, 2023

Have comments or feedback? I'd love to hear from you.