Wednesday, August 22, 2012

Creating a Menu in Unix Shell Script

Today I learned how to create a menu to display and choose from the menu. It has became a Menu driven program. which internally function based on your choice:-

Below is the sample script.


#!/bin/sh
# Wedding guest meals
# These variables hold the counters.
NUM_CHICKEN=0
NUM_STEAK=0
ERR_MSG=""
# This will clear the screen before displaying the menu.
clear
while :
do
        # If error exists, display it
        if [ "$ERR_MSG" != "" ]; then
                echo "Error: $ERR_MSG"
                echo ""
        fi
        # Write out the menu options...
        echo "Chicken: $NUM_CHICKEN"
        echo "Steak: $NUM_STEAK"
        echo ""
        echo "Select an option:"
        echo " * 1: Chicken"
        echo " * 2: Steak"
        echo " * 3: Exit"
        # Clear the error message
        ERR_MSG=""
        # Read the user input
        read SEL
        case $SEL in
                1) NUM_CHICKEN=`expr $NUM_CHICKEN + 1` ;;
                2) NUM_STEAK=`expr $NUM_STEAK + 1` ;;
                3) echo "Bye!"; exit ;;
                *) ERR_MSG="Please enter a valid option!"
        esac
        # This will clear the screen so we can redisplay the menu.
        clear
done


Execution:-

Call the script - ./menu.sh

Below will be shown on the screen, Now choose the option.. say I choose 1 then then counter for chicken will counter to 1 and so on..

Chicken: 0
Steak: 0
Select an option:
 * 1: Chicken
 * 2: Steak
 * 3: Exit

No comments:

Post a Comment