Guides:Shells/sh-bash/Loops

From CoderGuide

Jump to: navigation, search

Loops

Loops are another important part any programming language. The Bourne (sh) and Bourne Again (bash) shells are no exception. There are three loops used in the Bourne shell: while, until, and for.

While and Until Loops

while and until loops take the same format, however, the while loop executes while the expression is true, and the until loop runs while the expression is false (it runs until the expression is true, then stops). The expression takes the same format as those used in the if statements.

while [ "$var" -le 10 ]
do
  statements
done

until [ "$var" -le 10 ]
do
  statements
done

All loops use do and done keywords to indicate the start and end of a loop. You can break out of a loop by using break.

For Loops

For loops are used when you have a command you want to repeat, but need different values for a variable (any value). The for loop takes the following format:

for var in val1 val2 val.. do; command; done

When the for loop executes, val1 is assigned to the variable var. The next time the loop runs, val2 will be assigned to the variable.

The for loop is very effective when an operation needs to be performed on multiple files. I often type for loops in on the command line to perform manipulations on files. Nearly all statements in a shell script, including defining functions, can be typed in at the command prompt. If the shell expects more information, then it will prompt you for more (usually with a prompt that looks like " >").

Here is a for loop that will decompress all .tar.bz2 files into the /usr/src directory:

for file in *.tar.bz2
do
   (cd /use/src;tar jx) <"$file"
done

It's generally a good idea to put a variable in quotes when accessing it's value, because you don't know if it contains a space or not. Putting statements in parenthesis causes those statements to be executed in a sub shell. There are, of course, other ways to perform the same task without using a sub shell (save the current working directory with pwd and then change to /usr/src), but, when typing commands from the command prompt, the less you have to type to perform the same task, the better.

Another variation in the usage of the for construct, is where it is used without a list, like so:

for arg
do
   echo "$arg"
done

When used in this way, for will use the arguments passed to the script as the value list. This is similar to if you used "for file in $*", but a bit better (spaces won't cause the arguments to be split into two different values).

Personal tools