Sunday, February 16, 2014

Unix Shell Scripting–While Loop

- The while loop repeats the execution of a code block in the same way that the if statement conditionally executes a code block

- The syntax for the while loop is as follows

    while command  <—when command condition is true (status zero), then entered into loop

    do

        code block

     done

- The given code block will be repeatedly executed instill the given command returns an exit status that is non-zero

- Example

echo -n 'Please enter your answer : '

read answer

while [ "$answer" != tiger ]

do

      echo That answer is incorrect

      echo "Please try again, you entered $answer"

       read answer

done

Output:

Please enter your answer : Tiger
That answer is incorrect
Please try again, you entered Tiger
Chicken
That answer is incorrect
Please try again, you entered Chicken
tiger <—Exits the program as the condition is met, the while loop is not entered

Other Example:

echo -n "Please enter the directory name :"
read dir

while [ ! -d $dir ]
do
echo "You didn't enter a directory name"
echo -n "Please try again by entering a directory name :"
read dir
done

echo "Congratulation!! Your Directory Name is $dir"

Output:

Please enter the directory name :..
Congratulation!! Your Directory Name is ..

Please enter the directory name :sdfsdfdsf
You didn't enter a directory name
Please try again by entering a directory name :fdsg
You didn't enter a directory name
Please try again by entering a directory name :

- Using while loop we can pipe the output of a Unix command, read the values and loop them

Example:

Output of who command has 3 columns

- User – Details regarding the user who currently logged in

- Terminal – Details of the terminal the user is using

- Time – Details of time the user has logged in since.

[oracle@rac1 ~]$ who
oracle   tty1         2014-02-16 10:20 (:0)
oracle   pts/0        2014-02-16 10:20 (:0.0)

who | while read user term time
do
     echo $user is using $term logged in since $time

done

Output:

[oracle@rac1 ~]$ . PipedWhile
oracle is using tty1 logged in since 2014-02-16 10:20 (:0)
oracle is using pts/0 logged in since 2014-02-16 10:20 (:0.0)

- Break & Continue can be used in conjunction with while loop (for that matter any other loop in Unix Shell Programming)

Break – The break statement will cause the loop to immediately terminate. Execution will recommence with the next line after the done

Continue – The continue statement will cause the loop to abandon the current iteration of the loop and begin the next one (the loop condition is retested)

No comments:

Post a Comment