March 2012
Beginner to intermediate
230 pages
7h 27m
English
The while loop repeats a set
of commands as long as a condition is true.
whilecommandWhile the exit status of command is 0 dobodydone
For example, if this is the script myscript:
i=0 while [ $i -lt 3 ] do echo "$i" i=`expr $i + 1` done $ ./myscript 0 1 2
The until loop repeats until
a condition becomes true:
untilcommandWhile the exit status of command is nonzero dobodydone
For example:
i=0 until [ $i -ge 3 ] do echo "$i" i=`expr $i + 1` done $ ./myscript 0 1 2
The for loop iterates over
values from a list:
forvariableinlistdobodydone
For example:
for name in Tom Jack Harry do echo "$name is my friend" done $ ./myscript Tom is my friend Jack is my friend Harry is my friend
The for loop is particularly
handy for processing lists of files; for example, all files of a
certain type in the current directory:
for file in *.doc *.docx do echo "$file is a stinky Microsoft Word file" done
Be careful to avoid infinite loops, using while with the condition true, or until with the condition false:
while true Beware: infinite loop! do echo "forever" done until false Beware: infinite loop! do echo "forever again" done
Use break or exit to terminate these loops based on some
condition inside their bodies.
Read now
Unlock full access