Skip to Main Content
Linux Pocket Guide
book

Linux Pocket Guide

by Daniel J. Barrett
February 2004
Beginner content levelBeginner
200 pages
5h 40m
English
O'Reilly Media, Inc.
Content preview from Linux Pocket Guide

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 -gt 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
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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Pocket Guide, 2nd Edition

Linux Pocket Guide, 2nd Edition

Daniel J. Barrett
Linux in a Nutshell, 6th Edition

Linux in a Nutshell, 6th Edition

Ellen Siever, Stephen Figgins, Robert Love, Arnold Robbins

Publisher Resources

ISBN: 9780596806347Errata Page