Where while does its work as long as a certain condition is met, until is used for the opposite; it runs until the condition is met. You can see this in the example in Listing 27-23 where the script monitors whether the user whose name is entered as the argument is logged in.

Listing 27-23. Altering When a User Logs In

# script that alerts when a user logs in

# usage: ishere <username>

until who | grep $1 >> /dev/null do echo $1 is not logged in yet sleep 5

done echo $1 has just logged in

In this example, the command that is executed repeatedly is who | grep $1. In this command, the result of the who command that lists users currently logged in to the system is grepped for the occurrence of $1. As long as the command is not true, which is the case if the user is not logged in, the commands in the loop will be executed. At the moment the user logs in, the loop is broken, and a message is displayed indicating that the user has just logged in. Notice the use of redirection to the null device in the test; this makes sure the result of the who command is not echoed on the screen.

Sometimes it is necessary to execute a number of commands. The number of times can be limited; it can, however, be an unlimited amount of times. In such cases, loops with for can offer an excellent solution. Listing 27-24 shows how you can use for to run a counter.

Listing 27-24. Using for to Create a Counter

# counter that counts from 1 to 9 for (( counter=1; counter<10; counter++ )); do echo "The counter is now set to $counter"

done exit 0

The code used in this script is not difficult to understand. The conditional loop determines that as long as the counter has a value from 1 to 10, the variable counter must be incremented by 1 automatically. To do this, you can use the construction counter++, a technique with which a counter is incremented by 1. As long as this incrementing of the variable counter goes on, the commands between do and done are executed. In this case, it is a simple echo command; any other command will do as well. At the moment that the number that is specified has been reached, the loop is left, and the script will terminate and indicate with exit 0 to the system that it has done its work successfully.

Loops with for can be pretty versatile. For example, you can use for to do something on every line in a text file. The following illustrates how this works:

for i in scat /etc/passwd* do echo $i done

In this example, for displays all the lines in /etc/passwd one by one. Of course, just echoing the lines is a rather silly example, but the important thing is the way that for handles this. You should notice that if you are using for in this way, it cannot handle spaces in the lines. A space would be interpreted as a field separator, and therefore after the space, a new line would begin.

Was this article helpful?

0 0

Post a comment