Bourne/bash shell script: while loop syntax

Home -> Programming -> Shell script -> Bourne shells

134110 views

From the computer of: Rex (39 recipes)
Created: Jan 09, 2004     Updated: Aug 30, 2004


0 comments:
View all comments

Add a comment

Add to:
Add to stumbleuponAdd to del.icio.usDigg itAdd to FURL

A while loop allows execution of a code block an arbitrary number of times until a condition is met. This recipe describes the while loop syntax for the various Bourne shells (sh, ksh, bash, zsh, etc.) and provides examples.

General syntax:

while [ condition ]
do
    code block;
done


Any valid conditional expression will work in the while loop. The following code asks the user for input and verifies the input asking for a y or n and will repeat the process until a y answer is received.

verify="n"
while [ "$verify" != y ]
do
    echo "Enter option: "
    read option
    echo "You entered $option.  Is this correct? (y/n)"
    read verify
done


Another useful while loop is a simple one, and infinite loop. If the conditional is "1" the loop will run until something else breaks it (such as the break keyword):

while [ 1 ]
do
    ps -ef | grep [s]endmail | wc -l
    sleep 5
done


This while loop will display the number of sendmail processes running every five seconds until the loop or executing shell is killed. The brackets in [s]endmail are a regular expression trick that prevents the 'grep [s]endmail' process from being counted.

Subscribe to the Tech-Recipes Newsletter

You can get tips like this delivered in your email every week!

Enter your Email

We will never, ever sell your email address or spam you.





Related recipes:

  Bourne/bash shell script for loop syntax
  Bourne/bash shell scripts: case statement
  Bourne/bash shell script functions
  bash shell script iterate through array values
  Determine if a file is writable by a Bourne script user
  Bourne/bash shell scripts: if statement syntax
  Determine if file exists in a Bourne/bash shell script
  bash shell script accessing array variables
  Determine if a file is readable by current Bourne shell script user
  Hide password entry in Bourne/bash shell script

 

Sponsored links

 

Login

Nickname

Password

Don't have an account yet? You can create one. As a registered user you have some advantages like theme manager, comments configuration and post comments with your name.