Highland Linux User Group

Linux Community
It is currently Sun May 20, 2012 4:37 pm

All times are UTC [ DST ]




Post new topic Reply to topic  [ 1 post ] 
Author Message
 Post subject: Bash While Loop Example
PostPosted: Wed Feb 17, 2010 6:34 pm 
Offline
Moderator
User avatar

Joined: Tue Oct 03, 2006 12:27 pm
Posts: 167
Location: Inverness UK
Q. How do I use bash while loop to repeat certain task under Linux / UNIX operating system?

A. Bash while loop is a control flow statement that allows code or commands to be executed repeatedly based on a given condition. For example, run echo command 5 times or read text file line by line or evaluate the options passed on the command line for a script.
while loop syntax

Code:
while [ condition ]
do
   command1
   command2
   command3
done

command1 to command3 will be executed repeatedly till condition is true. The argument for a while loop can be any boolean expression. Infinite loops occur when the conditional never evaluates to false. For example following while loop will print welcome 5 times on screen:
Code:
#!/bin/bash
x=1
while [ $x -le 5 ]
do
  echo "Welcome $x times"
  x=$(( $x + 1 ))
done

Here is a sample shell code to calculate factorial using while loop:

Code:
#!/bin/bash
counter=$1
factorial=1
while [ $counter -gt 0 ]
do
   factorial=$(( $factorial * $counter ))
   counter=$(( $counter - 1 ))
done
echo $factorial


To run just type:
$ chmod +x script.sh
$ ./script.sh 5
Output:

120

While loops are frequently used for reading data line by line from file:

Code:
#!/bin/bash
FILE=$1
# read $FILE using the file descriptors
exec 3<&0
exec 0<$FILE
while read line
do
   # use $line variable to process line
   echo $line
done
exec 0<&3


You can easily evaluate the options passed on the command line for a script using while loop:

......
..
while getopts ae:f:hd:s:qx: option
Code:
do
        case "${option}"
        in
                a) ALARM="TRUE";;
                e) ADMIN=${OPTARG};;
                d) DOMAIN=${OPTARG};;
                f) SERVERFILE=$OPTARG;;
                s) WHOIS_SERVER=$OPTARG;;
                q) QUIET="TRUE";;
                x) WARNDAYS=$OPTARG;;
                \?) usage
                    exit 1;;
        esac
done

.......
Reference: http://www.cyberciti.biz/faq/bash-while-loop/

_________________
Computers are like air conditioners, They stop working properly when you open Windows!


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

All times are UTC [ DST ]


Who is online

Users browsing this forum: No registered users and 4 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
cron
Powered by phpBB® Forum Software © phpBB Group