Shell Script Programming - Loops

Category: Linux

I'm just starting to program shell scripts in Linux. I can handle basic IF ... THEN ... ELSE stuff, but I'm having trouble with looping? Can you give me some examples?

Shell scripts written in Bash (a common Linux command prompt shell) can implement looping, or iteration, with the while, until, and for constructs. In each case, a block of code is executed repeatedly until a loop exit condition is satisfied. The script then continues on from that point.

The while Statement

In a while loop, the block of code between the do and done statements is executed so long as the conditional expression is true. Think of it as saying, "Execute while this condition remains true." Here's an example:

while [ "$*" != "" ]
do
  echo "Argument value is: $1"
  shift
done

This trivial example prints the value of each argument passed to the shell script. Translated to English, the while condition says to continue so long as the input argument string is not null. You could also code the while statement as

while [ -n "$*" ]

but I think the first method is much easier to read and understand.

You might think that this loop would continue to print the first argument ($1) forever and ever, since you don't expect the value of the $* variable (the list of arguments from the command line) to change during the course of running the script. You'd be right, except that I slipped the shift command into the body of the loop.

What shift does is discard the first argument and reassign all the $n variables--so the new $1 variable gets the value that used to be in $2, and so on. Accordingly, the value in $* gets shorter and shorter each time through the loop, and when it finally becomes null, the loop is done.

The until Statement

The until construct works almost exactly the same as while. The only difference is that until executes the body of the loop so long as the conditional expression is false, whereas while executes the body of the loop so long as the conditional expression is true. Think of it as saying, "Execute until this condition becomes true."

Let's code the previous example using an until loop this time and making it a little fancier by adding a counter variable:

count=1
until [ "$*" = "" ]
do
  echo "Argument number $count : $1 "
  shift
  count=`expr $count + 1`
done

Again, you could have coded the until statement as

until [ -z "$*" ]

but I recommend not using the -n and -z operators because it's harder to remember what they do.

The only new concept here is the strange-looking line that increments the counter:

count=`expr $count + 1`

The expr command signals to the shell that we're about to perform a mathematical calculation instead of a string operation. And the doodads that look kind of like single quotation marks are not--they're the backtick (`) character, found to the left of the number 1 key on most keyboards. By enclosing an expression in backticks, you tell the shell to assign the result of a Linux command to a variable, instead of printing it to the screen.

Note: The spaces on either side of the plus sign are required.

The for Statement

The for statement is yet another way to implement a loop in a shell script. The general form of the for construct is shown here:

for item in list
do
  something useful with $item
done

Each time through the loop, the value of the item variable is assigned to the nth item in the list. When you've processed all the items in the list, the loop is done. Here's an example similar to the until and while loops you saw earlier in this section:

for $item in "$*"
do
  echo "Argument value is: $item"
done

More Help With Linux Programming

My LowFat Linux website is a series of tutorials on using Linux. It covers all the basics, including Linux commands, manipulating files & data, Linux programming, and basic unix system administration.

Here's the chapter on Linux Shell Programming: http://www.lowfatlinux.com/linux-shell-script.html

And you may also want to check out Perl Programming Basics: http://www.lowfatlinux.com/linux-perl-basics.html

 
Ask Your Computer or Internet Question

 
  (Enter your question in the box above.)

It's Guaranteed to Make You Smarter...

AskBob Updates: Boost your Internet IQ & solve computer problems.
Get your FREE Subscription!


Email:

Check out other articles in this category:



Link to this article from your site or blog. Just copy and paste from this box:

This article was posted by on 12 Dec 2005


For Fun: Buy Bob a Snickers.

Prev Article:
Digital Music and Lyrics

The Top Twenty
Next Article:
Create Currency Quickly

Most recent comments on "Shell Script Programming - Loops"

Posted by:

Willie
21 Jul 2007

How do I find the adv of two numbers. and put it in a loop.

trying to find example to help me get linux shell. thank you.

EDITOR'S NOTE: Did you mean "average"? Here's how to find the average of two numbers... not sure what you mean by putting it in a loop.

let x=$1+$2;

let y=$x/2;

echo "Average of $1 and $2 is $y";


Post your Comments, Questions or Suggestions

*     *     (* = Required field)

    (Your email address will not be published)
(you may use HTML tags for style)

YES... spelling, punctuation, grammar and proper use of UPPER/lower case are important! Comments of a political nature are discouraged. Please limit your remarks to 3-4 paragraphs. If you want to see your comment posted, pay attention to these items.

All comments are reviewed, and may be edited or removed at the discretion of the moderator.

NOTE: Please, post comments on this article ONLY.
If you want to ask a question click here.


Free Tech Support -- Ask Bob Rankin
Subscribe to AskBobRankin Updates: Free Newsletter

Copyright © 2005 - Bob Rankin - All Rights Reserved
Privacy Policy     RSS/XML


Article information: AskBobRankin -- Shell Script Programming - Loops (Posted: 12 Dec 2005)
Source: https://askbobrankin.com/shell_script_programming_loops.html
Copyright © 2005 - Bob Rankin - All Rights Reserved