February 2004
Beginner
204 pages
5h 40m
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 -gt 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 do echo "$file is a stinky Microsoft Word file" done
For an infinite loop, use while with the condition true, or until with the condition false:
while true do echo "forever" done until false do echo "forever again" done
Presumably you would use break or exit to terminate these loops based on some condition.
Read now
Unlock full access