Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm trying to write a bash script which asks the user to select two options. If the user selects the option within the scope of available options, then script goes fine. But if the user enters an invalid option, I can only exit the script echoing user that the option is invalid. Can i write the script in such a way that if user enters invalid option, the script should re-prompt the user to provide correct option again..

Here is what the script looks like.

#!/bin/bash

echo "Please select the correct option."

echo "Valid options are 0 and 1"

read userinput

if [ $userinput -eq 0 ]

then

# do this

elif [ $userinput -eq 1 ]

then

# do this.

else

exit

# needs to be replaced to start from "read userinput" again.

fi

share|improve this question
    
You might want to look at the following question stackoverflow.com/questions/9639103/… you basically need a loop. –  Ramhound Aug 29 '13 at 17:15

2 Answers 2

up vote 1 down vote accepted

You could try something like this (notice that I am using string comparisons, your users might enter a letter instead of a number so using -eq is not a good idea):

#!/bin/bash
echo -e "Please select the correct option.\nValid options are 0 and 1"
ok=0;
while [ "$ok" = "0" ] ; do
    read userinput

    if [ "$userinput" = "0" ]
    then
      # do this
      ok=1;
    elif [ "$userinput" = "1" ]
    then
      ok=1
      # do this.
    else
      echo "Invalid option, please choose either 1 or 0."
    fi
done
share|improve this answer
    
Perfect. I just needed this. –  james Aug 29 '13 at 17:38

You probably want to do an until type of statement. You'll get the input and test for it to be valid. It will continue to run until a condition is met (i.e. the input is valid).

Here is another reference for until.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.