Spring Into Linux

A for loop repeats commands once for each item in a list of arguments. The general format of a for loop is:

for index in list do commands done

The index is a variable name. It takes on a value from the list with each iteration of the loop. The list is a list of arguments through which for loops. A simple for loop is:

for name in John Sam Paul do echo $name done

Items in the list can be separated by a space or by the end of a line.

You can provide the for loop with a list of arguments by executing a command. For instance, the following script processes the output of the date command.

#!/bin/bash # Script name: splitdate - outputs parts of the date in a column for part in `date` do echo $part done

When you run the script, you see:

./splitdate Mon Jan 10 15:02:34 PST 2005

Another way to create a list of arguments is to store them in a file and read the file, as follows:

for item in `cat file1` do echo $item done

If you leave out the in parameter, the script looks for the list in the numbered variables, assuming you entered a list on the command line. Thus, you can use the following syntax to enter your list at the command line:

for name do echo $name done

Then run the script with:

./listnames John Sam Paul John Sam Paul

The for loop is useful for processing each file in a directory. The following for loop echoes each file in the current directory:

for file in * do if [ ! -s $file ] then echo Removing $file rm $file fi done

The code tests whether the file is empty. If it's empty, the filename displays and the file is deleted.

The * represents all files in the current directory. You can specify a different directory with the line below:

for file in /home/janet/*

    Категории