O'Reilly logo

Linux Pocket Guide, 2nd Edition by Daniel J. Barrett

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Loops

The while loop repeats a set of commands as long as a condition is true.

while command             While the exit status of command is 0
do
  body
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:

until command         While the exit status of command is nonzero
do
  body
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:

for variable in list
do
  body
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 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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required