The for-do-done loop is executed on a list of elements. The list of elements is assigned to a variable one-by-one. The value of this variable is processed inside the loop. The loop continues to execute until all of the list elements are processed and there are no more elements in the list. The general syntax of the for-do-done loop is:
for var in list do command block done
The for-do-done loop flow diagram is shown in Figure 11-3.
As an example of the use of this loop, if you want to list all executable files in your home directory, you can use the following program ( script-23 ) for this purpose.
#!/usr/bin/sh echo "List of all executable files in home directory" cd $HOME for F in * do if [ -x $F ] then ll $F fi done
The asterisk character represents all files in this directory. When you run this program, the result is shown as follows . You may have a different result on your system. There may be other uses of this program. You can utilize this script to find all files that have the SUID bit set or some other type of file with slight modifications.
$ ./script-23 List of all executable files in home directory -rwxr-xr-x 1 boota users 267 Oct 18 19:23 script-00 -rwxr-xr-x 1 boota users 131 Oct 18 19:53 script-01 -rwxr-xr-x 1 boota users 198 Oct 18 20:01 script-02 -rwxr-xr-x 1 boota users 100 Oct 18 20:07 script-03 -rwxr-xr-x 1 boota users 121 Oct 18 20:16 script-04 -rwxr-xr-x 1 boota users 132 Oct 18 21:25 script-05 -rwxr-xr-x 1 boota users 232 Oct 18 23:11 script-06 -rwxr-xr-x 1 boota users 177 Oct 18 22:04 script-07 -rwxr-xr-x 1 boota users 142 Oct 19 17:43 script-08 -rwxr-xr-x 1 boota users 170 Oct 19 18:04 script-09 -rwxr-xr-x 1 boota users 638 Oct 19 18:30 script-10 -rwxr-xr-x 1 boota users 313 Oct 19 19:31 script-11 -rwxr-xr-x 1 boota users 195 Oct 20 23:16 script-20 -rwxr-xr-x 1 boota users 193 Oct 20 23:00 script-21 -rwxr-xr-x 1 boota users 195 Oct 21 17:04 script-22 -rwxr-xr-x 1 boota users 140 Oct 21 17:07 script-23 $
The script-24 is another example of the for-do-done loop, where a list is provided to the for command. This list contains the names of weekdays, which the program reads one-by-one and prints them on your terminal screen.
#!/usr/bin/sh for DAY in Sunday Monday Tuesday Wednesday Thursday Friday Saturday do echo "The day is : $DAY" done
The result of this program is:
$ ./script-24 The day is : Sunday The day is : Monday The day is : Tuesday The day is : Wednesday The day is : Thursday The day is : Friday The day is : Saturday $
Let's suppose you want to change the access time of all files in your current directory to the current time. You can use the touch command with a small shell script as shown here.
for FILE in * do touch $FILE done
To process all command line parameters one-by-one using a for-do-done loop, the following code segment may be used.
for ARG in $* do echo $ARG done
You can replace the echo command with any command or a block of commands to get a desired result.
Study BreakUse of Shell Loops
|
Top |