Question

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.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top