Книга: Fedora™ Unleashed, 2008 edition
The while Statement
The while
Statement
The while
statement can be used to execute a series of commands while a specified condition is true. The loop terminates as soon as the specified condition evaluates to False
. It is possible that the loop will not execute at all if the specified condition initially evaluates to False
. You should be careful with the while
command because the loop will never terminate if the specified condition never evaluates to False
.
Endless Loops Have Their Place in Shell Programs
Endless loops can sometimes be useful. For example, you can easily construct a simple command that constantly monitors the 802.11b link quality of a network interface by using a few lines of script:
#!/bin/sh
while :
do
/sbin/iwconfig eth0 | grep Link | tr 'n' 'r'
done
The script outputs the search, and then the tr
command formats the output. The result is a simple animation of a constantly updated single line of information:
Link Quality:92/92 Signal level:-11 dBm Noise level:-102 dBm
This technique can also be used to create a graphical monitoring client for X that outputs traffic information and activity about a network interface:
#!/bin/sh
xterm -geometry 75x2 -e
bash -c
"while :; do
/sbin/ifconfig eth0 |
grep 'TX bytes' | tr 'n' 'r' ;
done"
The simple example uses a bash
command-line script (enabled by -c
) to execute a command line repeatedly. The command line pipes the output of the ifconfig
command through grep
, which searches ifconfig
's output and then pipes a line containing the string "TX bytes
" to the tr
command. The tr
command then removes the carriage return at the end of the line to display the information inside an /xterm
X11 terminal window, automatically sized by the -geometry
option:
RX bytes:4117594780 (3926.8 Mb) TX bytes:452230967 (431.2 Mb)
Endless loops can be so useful that Linux includes a command that repeatedly executes a given command line. For example, you can get a quick report about a system's hardware health by using the sensors
command. But rather than use a shell script to loop the output endlessly, you can use the watch
command to repeat the information and provide simple animation:
$ watch "sensors -f | cut -c 1-20"
In bash
, the following format is used for the while
flow-control construct:
while expression
do
statements
done
If you want to add the first five even numbers, you can use the following shell program in bash
:
#!/bin/bash loopcount=0 result=0
while [ $loopcount -lt 5 ] do
loopcount=`expr $loopcount + 1`
increment=`expr $loopcount * 2`
result=`expr $result + $increment`
done
echo "result is $result"