Using GNU/Linux through creative laziness (and other topics as they strike my fancy)
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:
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.)
If you want to loop through an array literally you can do it like this:
ReplyDeletefor i in file1 file2 file3
do
...
done
thanks for documenting syntax. I wish I knew what the @ sign is doing. is the another variable indicator like $?
ReplyDeleteanyway I plan to write a script to remove my log and aux files after compiling a xelatex document.
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.)
ReplyDelete