For Loops
A for loop repeats commands once for each item in a list of arguments. The general format of a for loop is:
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 index in list
do
command s
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.
for name in John Sam Paul
do
echo $name
done
When you run the script, you see:
#!/bin/bash
# Script name: splitdate - outputs parts of the date in a column
for part in `date`
do
echo $part
done
Another way to create a list of arguments is to store them in a file and read the file, as follows:
./splitdate
Mon
Jan
10
15:02:34
PST
2005
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 item in `cat file1`
do
echo $item
done
Then run the script with:
for name
do
echo $name
done
The for loop is useful for processing each file in a directory. The following for loop echoes each file in the current directory:
./listnames John Sam Paul
John
Sam
Paul
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 *
do
if [ ! -s $file ]
then
echo Removing $file
rm $file
fi
done
for file in /home/janet/*