0

Ok, so i have tried searching for this on google and i cant seem to find an answer. What i'm trying to do is create a case statement in bash but if the user enters a different number than listed it just exits the script. How do i make it give an error and then ask for the user to select one of the options?

for example, my case statement

case $ans in
1) echo "Running Project 1..."
   sleep 2
   ./project1.sh
;;
2) echo "Running Project 2..."
   sleep 2
   ./project2.sh
;;
Qq) echo "Exiting"
    exit
;;
esac

so any options other than 1, 2, Qq it will give an error saying invalid selection, try again.

2
  • I just tried wrapping an if statement around case statment and it still doesn't work, maybe my if statement is wrong? if [ $ans == "1" || $ans == "2" || $ans == "q" || $ans == "Q" ] Commented Dec 3, 2013 at 14:21
  • You might also want to take a look at the select statement. Commented Dec 3, 2013 at 14:40

1 Answer 1

1

You need a while loop and a boolean variable like that:

flag = true
while [  $flag ]; do
    case $ans in
        1) echo "Running Project 1..."
           sleep 2
           ./project1.sh
        ;;
        2) echo "Running Project 2..."
           sleep 2
           ./project2.sh
        ;;
        Qq) echo "Exiting"
            flag = false
        ;;
    esac
done
Sign up to request clarification or add additional context in comments.

4 Comments

initially this did not work for me but then i moved my read statment for $ans inside the loop and it works. However, the when i try to quit the Qq no longer works. but if i take one q out the other works. Without creating a 4th case option, how do i keep it to its Q or q ?
I'm not sure if this is the proper way or not but i changed Qq) to Q|q) and it seems to work just fine.
Yes, you are right as you can see here the syntax of OR between two patterns
also i changed the while loop around a bit. First for the Q|q) choice instead of having it exit from that choice i had it set the flag to false. In the while loop i changed it to while [ $flag = "true" ];do instead, so once the exit choice is selected it changes the value to false and the loop exits. This way allows me to run more commands if i need to.

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.