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:
/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' ; \
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 will repeatedly execute a given command line. For example, you can get a quick report about a system's hardware health by using the sensors command. But instead of using a shell script to loop the output endlessly, you can use the watch command to repeat the information and provide simple animation:
In pdksh and bash, the following format is used for the whiie flow control construct:
whiie expression do statements done
In tcsh, the following format is used:
whiie (expression) Statements end
If you want to add the first five even numbers, you can use the following shell program in pdksh and bash:
#!/bin/bash loopcount=0 result=0
while [ $loopcount -lt 5 ] do loopcount=Nexpr $loopcount + iN increment=Nexpr $loopcount \* 2N result=Nexpr $result + $incrementN done echo "result is $result"
In tcsh, this program can be written as follows:
#!/bin/tcsh set loopcount = 0 set result = 0 while ($loopcount < 5)
set loopcount = Nexpr $loopcount + iN set increment = Nexpr $loopcount \* 2N set result = Nexpr $result + $incrementN
end echo "result is $result"
Was this article helpful?