Loops
The while
loop repeats a set of commands as long as a
condition is true:
whilecommand
While the exit status of command is 0 dobody
done
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:
untilcommand
While the exit status of command is nonzero dobody
done
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:
forvariable
inlist
dobody
done
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 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.
Get Macintosh Terminal Pocket Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.