Advanced Shell Topics: For loops


There are many different shell based control structures that I could introduce in this presentation. The only one I'll really go into depth on is for loops because they have a lot of use from within the shell itself.

For loops are a way to iterate a set of intructions on an array of values. It can be used to quickly run commands on multiple files, directories or other commands.

[user@host ~]$ for x in 5 4 3 2 1 ; do echo $x ; done
5
4
3
2
1
[user@host ~]$

The above is the basic syntax of a for loop. The second word specifies what the name of the variable you are going to use is. The loop itself uses all the values inbetween the word 'in' and the first semicolon. In this case, the first run of the loop will set x to 5, the second time x will be 4 and so on. The word do precedes the list of commands that you wish to run for each iteration of the loop. And finally, you put '; done' at the end of the command line to indicate where the commands (and the loop statement) ends.

The commands run by the loop itself don't even need to use the value of the variable. If you just wanted to run a command 5 times and wait one minute between each invocation of the command you could do so.

[user@host ~]$ for x in 1 1 1 1 1 ; do mpg123 rockabilly.mp3 ; sleep 60 ; done
[user@host ~]$      

Since there are five 1s in the array sequence it will go through the loop five times, setting x to 1 each time. But none of the commands use the variable x anywhere.

It is also useful to use the output of a command as the input to the array sequence for the loop, this is done by using the backtick characters to run a command in place of the array section:

[user@host ~]$ for x in `ls -1 *.phtml` ; do chmod -v o+w $x ; done
mode of bangcharacter.phtml changed to 0646 (rw-r--rw-)
mode of footer.phtml changed to 0646 (rw-r--rw-)
mode of forloops.phtml changed to 0646 (rw-r--rw-)
mode of grep.phtml changed to 0646 (rw-r--rw-)
mode of header.phtml changed to 0646 (rw-r--rw-)
mode of index.phtml changed to 0646 (rw-r--rw-)
mode of ioredirect.phtml changed to 0646 (rw-r--rw-)
mode of jobcontrol.phtml changed to 0646 (rw-r--rw-)
mode of movement.phtml changed to 0646 (rw-r--rw-)
mode of regularexpressions.phtml changed to 0646 (rw-r--rw-)
mode of shellvariables.phtml changed to 0646 (rw-r--rw-)
[user@host ~]$ 

The -1 option to ls lists the filenames as a single column and those arguments get passed as the array elements to the for loop.


© 2000 Suso Banderas - suso@suso.org