MLUG Bash Scripting Workshop 25/04/08
Prev Index Next

Flow Control

I am going to give you another script to play with but before I do that I will need to explain a few more things on this and the next page

The first thing I want to talk about is managing flow control in scripts with the Bash built-ins case and while.

In the if statements we have looked at we were altering the flow of the script, that is, depending on the condition we set, the script executed one set of commands or another set of commands. If has its limitations and in some instances case will be more suited to the job.

The script below is a case statement. It will proceed down the list until it finds a match then do what is required. " * " is used to catch anything that doesn't match. Note that this script will stop at read and will not resume until Bash receives a newline (Enter) presumably preceeded by a string.

I did not include this as an example script but you can copy it, paste it into a file and run it easily enough if you like.


#!/bin/bash
echo -n "Enter e\numbers 1,2 or 3"
read response
case $response in
	1 ) echo "You entered one."
	;;
	2 ) echo "You entered two."
	;;
	3 ) echo "You entered three."
	;;
	* ) echo "You did not enter a number"
	;;
esac
#end of script

In the script below a loop is set up with while and the commands within the loop will repeat until the condition is met and the script breaks out of the loop. I'll explain how it works:


#!/bin/bash

number=0
while [ $number -lt 10 ]; do
    echo "Number = $number"
    number=$number
done

#end of script

I have expanded this script into something a little more interactive in example05. Run it and play with it.

Note: It is possible to inadvertently create a loop with while that will not terminate, a.k.a an infinit loop and this can eat up resources fast. I have written a script that goes into an infinit loop named fool. It's in the scripts directory. Run it in a console then run top in a second console and check out the revs on the CPU!

CTRL C or killall fool in another terminal will kill the process when you've had enough.


Top