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"
Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.$$ Check price
Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.$ Check price