Sunday, January 20, 2008

A continuous menu


If you need to write a small script to run your "tests suite", I am presenting here an efficient way(I feel so) of writing a menu.

while : # Loop forever

do
cat << !

R U N M E N U

1. Regression Tests
2. Smoke Tests
3. Other Tests
4. Run All Tests
5. Quit

!
echo -n " Your choice? : "
read choice

case $choice in
1) some operation ;;
2) some operation ;;
...
5) clear; exit ;;
*) echo; echo "\"$choice\" is not a valid option."; sleep 2 ;;
esac
done

The other way of making a continuous menu is to have a variable set to "no", and exit the menu when the value is "yes" (set the value to "yes" for the quit option in the menu like below):

quit="no"
while [ $quit != "yes" ]

do

echo "1. Regression Tests"
echo " 2. Smoke Tests"
...
...
echo " 5. Quit"
echo -n " Your choice? : "
read choice

case $choice in
1) do something ;;
...
...
5) quit="yes" ;;
*) echo; echo "\"$choice\" is not a valid option."; sleep 2 ;;

esac
done

And for a situation where your program have to display a lot of menus, we can think of a function to generate a menu of a set of options like below:

#Construct Menu
f_ConsMenu() {
clear
while :
do
echo $1 | awk -F "+" '{print $1}'
echo $1 | awk -F "+" '{for (i=2;i<=NF;i++) {print i-1")",$i}}'

echo -n "Your Choice ? " ; read choice
return $choice
done

}

f_ConsMenu "MAIN MENU"+"Insert"+"Delete"+"Update"+"Quit"
case $choice
in
1) do something ;;
2) do something ;;
...
...
esac

The output will be something like this :
MAIN MENU
1) Insert
2) Delete
3) Update
4) Quit
Your Choice ?

No comments:

© Jadu Saikia www.UNIXCL.com