Loops in the UNIX Shell - More loops
(Page 3 of 4 )
The second loop structure is the "while." For this, the condition that must be met to continue is similar to the "if."
The syntax of this is:
while command_line_condition
do
command line
...
done
In addition:
until command_line_condition
do
command line
...
done
The "until" is just an opposite while. Therefore we use the while loop more often, but more than likely we will negate the while, then use the "until." For the command line condition, we can use any command line or the test command I presented in the previous article as well:
i=1;
while [ "$i" -lt 10 ]
do
i = $(expr "$i" * 2 )
done
This will calculate two to the power of four. Of course, we can do more complicated and useful tasks with this loop. However, for this I need to present the read command first. This will read a value from the standard input. Using the pipe system, we can also read in line after line from a file. For instance, the example below will read in line after line until it finds the finish string:
while [ "$in" != "finish" ]
do
read in
# do whatever you want with the data
...
done
You can consider the while loop as a single command. The command starts with the string while, and ends with the done. If you think about what this means, you'll see that we can direct to it any data stream for processing. We can use the cat command to read in from a file, and then use the read command to extract line after line from the input stream. This will show you an example:
cat alfa.txt | while read line
do
$do what you want with the line
done
A second impact of thinking of the while loop like a command is that it will be executed inside a sub-shell. As I explained earlier, the while will only get the stream, and for its execution, a new shell will be started. Therefore, any variable you will use inside the while will not be present outside the while.
An alternative way to process a file is by using the redirection method:
while read line
do
echo $line
done < alfa.txt
I recommend using the "until" function only when you want to execute something until a variable gets a value assigned to it. If you want to delete a variable from the shell's variable list, you can use the unset command. However, within shell script writing, choosing the appropriate loop is relative and left to the user. The following example will obligate you to enter the text Yeti. Any other option will throw you back to read in a new line.
until [ $variable ]
do
read variable
if [ $variable != "Yeti" ]
then
unset variable
fi
done
Next: Controlling the loops >>
More Miscellaneous Articles
More By Gabor Bernat