While-loops are much like for-loops, and continue to iterate until the exit status of the condition is false. While-loops consist of the following syntax:
while [ condition exits successfully ] do # Commands here done
A common use of the while-loop is to iterate through shell arguments, to obtain all option arguments. Each call to the
shift command helps us go down the list of options, with the arguments going down one by one. This causes the value of
$1 to be replaced by
$2 to be replaced by
$3, and so on.
Here's a script of how we can combine a while-loop with a case-statement to iterate through all options.
#!/bin/bash while [ $# -gt 0 ] do case $1 in # File option, followed by filename -f) filename=$2 shift ;; -v) verbose=true quiet= ;; -q) quiet=true verbose= ;; -l) long=true ;; # Unrecognized option -*) echo "$0: $1: unrecognized option" >&2 ;; **) break ;; esac # shift for next option shift done
Another helpful command that is often seen with while-loops is
getopts. This command follows standard POSIX option syntax (single letters preceded by a
- and possibly one argument value).
For each option that contains an argument, we use the colon (
:). For example, we can have
a:bc if we plan to have the
-a option contain an argument. An example call would look something like:
$ ./test -a argumentValue -b -b
argumentValue goes with the
In this example, we design a timer that has several options a user can specify.
#!/bin/bash if [ $# -lt 1 ] then echo "Usage: $0 -t -m -a -r" echo "-t time (in seconds)" echo "-m message at countdown" echo "-a author" echo "-r repeat n number of times" exit 1 fi # Set default parameters seconds=5 message="Time's up!" author="anonymous" repeatNumber=1 # Need to have a colon (:) after each option that has | an argument. while getopts t:m:a:r: opt do case $opt in t) seconds=$OPTARG;; m) message=$OPTARG;; a) author=$OPTARG;; r) repeatNumber=$OPTARG;; esac done for iterationNumber in $(seq 1 $repeatNumber) do echo "Repeating $iterationNumber of $repeatNumber | times!" for sec in $(seq $seconds 1) do echo "Countdown: $sec" sleep 1 done done echo "$message by $author"
This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.$ Check price
The Linux Command Line takes you from your very first terminal keystrokes to writing full programs in Bash, the most popular Linux shell. Along the way you'll learn the timeless skills handed down by generations of gray-bearded, mouse-shunning gurus: file navigation, environment configuration, command chaining, pattern matching with regular expressions, and more.$ Check price