23 March 2008

iterating through an array in bash

Every now and then I need to iterate through an array of items in a bash script, and I can never remember the syntax--I always have to look it up. So here's a quick example...

#!/bin/bash

things=( first second third )

for i in ${things[@]}
do
echo $i
done


If the number of array elements is large, it can be useful to have one element per line:

things=( \
first \
second \
third \
)

3 comments:

Sam said...

If you want to loop through an array literally you can do it like this:

for i in file1 file2 file3
do
...
done

macmadness86 said...

thanks for documenting syntax. I wish I knew what the @ sign is doing. is the another variable indicator like $?

anyway I plan to write a script to remove my log and aux files after compiling a xelatex document.

mbrisby said...

The @ symbol is an array subscript which causes the word (things[@]) to expand to all members of the things array. (See the "Arrays" section of the bash man page.)