Using ‘while’ in the bash shell
I like to use while loops to perform a command or group of commands indefinitely until I type ctrl-c to stop the loop. The while loop is useful when monitoring the output of the netstat command
while [ TRUE ]; do netstat -an | grep 80; echo "#######"; sleep 2; done
Alternatively, the above one-liner can be written into a script, as follows:
while [ TRUE ] do netstat -an | grep 80 echo "#######" sleep 2 done
The above scriptlet will execute the netstat command, looking for the number 80 every two seconds and prints a delineation between each instance of the command. So the output might look something like this:
user@host[~]# while [ TRUE ]; do netstat -an | grep 80; echo "#######"; sleep 2; done tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN tcp 0 0 67.225.246.15:80 173.71.196.168:9971 ESTABLISHED tcp 0 0 67.225.246.15:80 107.23.211.53:46294 TIME_WAIT ####### tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN tcp 0 0 67.225.246.15:80 173.71.196.168:9971 ESTABLISHED tcp 0 0 67.225.246.15:80 107.23.211.53:46294 TIME_WAIT ####### tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN tcp 0 0 67.225.246.15:80 173.71.196.168:9971 ESTABLISHED tcp 0 0 67.225.246.15:80 107.23.211.53:46294 CLOSE ####### tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN tcp 0 0 67.225.246.15:80 173.71.196.168:9971 ESTABLISHED tcp 0 0 67.225.246.15:80 107.23.211.53:46294 CLOSE ####### ^C user@host[~]#
Another way to use the while loop is when you want to watch a file grow as it’s being written. In order to do this, just use the list command ‘ls -l filename’ in the loop.
while [ TRUE ]; do ls -l filename; sleep 5; done
In this case, we have omitted the delination between commands, and we increased the sleep time to 5 seconds so that we see the file size every 5 seconds. Here’s what the output might look like:
user@host[~]# while [ TRUE ]; do ls -l dumpfile; sleep 5; done -rw-r--r-- 1 root root 976029 Mar 16 2013 dumpfile -rw-r--r-- 1 root root 1448764 Mar 16 2013 dumpfile -rw-r--r-- 1 root root 2294374 Mar 16 2013 dumpfile -rw-r--r-- 1 root root 3020971 Mar 16 2013 dumpfile -rw-r--r-- 1 root root 3993570 Mar 16 2013 dumpfile -rw-r--r-- 1 root root 4850348 Mar 16 2013 dumpfile ^C user@host[~]#
Notes:
-
– You can also use while [ 1 ]; do something; done since the TRUE equates to 1.
– Be sure to use semi-colons between each statement if running it as a one-liner from the command-line
– Make sure there are spaces inside the brackets [ TRUE ] or it won’t work
Enjoy!
-Krnl