Examples of using the while and until statements

To wait for someone to logout:

   #!/bin/sh
   while who |grep -s $1 >/dev/null
   do
     sleep 60
   done
   echo "$1 has logged out"

This script checks to see if the username given as an argument to the script is logged on. While they are, the script waits for 60 seconds before checking again. When it is found that the user is no longer logged on a message that they have logged out is displayed.


To declare when a file has been created:

   #!/bin/sh
   until test -f $FILE
   do
     sleep 60
   done
   echo "$FILE now exists"

This tests every 60 seconds until the filename represented by the variable $FILE exists. A message is then displayed.


To watch for someone to log in:

   #!/bin/sh
   # make sure we pick up the correct commands
   PATH=/bin:/usr/bin
   # remember $# is number of positional arguments
   case $# in
   1) ;;
   *) echo 'usage: watchfor username' ; exit 1
   esac
   until who | grep -s "$1" >/dev/null
   do
     sleep 60
   done
   echo "$1 has logged in"

If more than one username is given to the command watchfor the message

   usage: watchfor username

is displayed and the command fails.


[Home] [Search] [Index] This site maintained by webmaster@cs.auckland.ac.nz