2

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

I updated my code as per your suggestion but it is still not working: echo -n "Please enter option [1 - 6]" read opts for opt in $opts; do case $opt in ............... esac done done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.