UNIX and Linux Shell Script For Loops

A common shell precedue is the "for loop" - an often used timesaver. Let’s jump straight into an example.

Example 1: Using a For Loop to change file ownership

Here, for each user in our list we change the ownership of their home directory. Note that the user variable is assigned by the first line of the for loop.


for user in fred bernard lisa frank 
do
	chown ${user}:staff /home/${user}
done

Note the special words, "for" and "in" on the first line. The list of items in the for loop cannot contain reseved words such as these. The full list of reserve words is:

if then else elif fi case in exac for while until do done {}

Example 2: Using a For Loop to describe a list of files

First we create a file called "explain" containing this text:


for filename 
do 
	file $filename
	ls -l $filename
done

Notice that we haven’t specified a list of items on the first line. The list of items will be parsed into the command when we call this file. We can use it to describe some files for us like this:

bash$ sh explain /etc/hosts /dev/sda
/etc/hosts: ASCII English text
-rw-r--r-- 1 root root 357 2008-12-11 11:32 /etc/hosts
/dev/sda: block special (8/0)
brw-rw---- 1 root disk 8, 0 2008-12-08 15:45 /dev/sda

Semi-colons can also be used to seperate the list of commands instead of newlines, so we could write the text of our "explain" command file like this if we wanted to:

for filename ; do file $filename ; ls -l $filename ; done

It would do exactly the same thing, however it is less readable so use semi-colons with caution!