sk2code
sk2code

Reputation: 31

Shell Script: Menu driven script taking in multiple options

I need some suggestions for my menu driven shell script. I would like the end user of this script to be able to provide multiple options when prompted to enter the choice. The user can also enter 1 option or he/she can enter multiple options.

For eg. the script should be able to handle both options:

Please enter any option or options between [1 - 4]: 1 2 3 

Please enter any option or options between [1 - 4]: 1

Please let me know how can I made changes to my script to reflect this.

Below is the code of my script for your reference:

#!/bin/sh

while :
do
 clear
 echo " ******** Task performing script ******** "
 echo "1. task1 "
 echo
 echo "2. task2 "
 echo
 echo "3. task3"
 echo
 echo "4. Exit"
 echo
 echo -n "Please enter any option or options between [1 - 4]"
     read opt;
 case $opt in
1)
 echo "Performing task1 . . . .";
 for i in `cat test`
 do
 ...............
 ...............
 done;;
2)
 echo "Performing task2 . . . .";
 for i in `cat test`
 do
 ...............
 ...............
 done;;
3)
 echo "Performing task3 . . . .";
 for i in `cat test`
 do
 ...............
 ...............
 done;;
4)
 echo "Bye $USER";
 exit 1;;
*)
 echo "$opt is an invaild option";
 echo "Press [enter] key to continue. . .";
 read enterKey;;
  esac
done

Upvotes: 2

Views: 5639

Answers (1)

chepner
chepner

Reputation: 531165

Wrap your case statement in a for loop that iterates over the value you get from the read statement.

while : do;
    # print menu
    read opts

    for opt in $opts; do  # To allow for multiple space-separated choices

        case $opt in
        ...
        esac
    done
done

Upvotes: 2

Related Questions