views:

12914

answers:

5

I want to pause input in a shell script, and prompt the user for choices. The standard 'Yes, No, or Cancel' type question. How do I accomplish this at a typical bash prompt?

+2  A: 
echo "Please enter some input: "
read input_variable
echo "You entered: $input_variable"
Pistos
A: 
inquire ()  {
  echo  -n "$1 [$2/$3]? "
  read answer
  finish="-1"
  while [ "$finish" = '-1' ]
  do
    finish="1"
    if [ "$answer" = '' ];
    then
      answer=""
    else
      case $answer in
        y | Y | yes | YES ) answer="y";;
        n | N | no | NO ) answer="n";;
        *) finish="-1";
           echo -n 'Invalid response -- please reenter:';
           read answer;;
       esac
    fi
  done
}

... other stuff

inquire ""Install now? " "y" "n"

...

Where'd my formatting go? I guess that shows what happens if you cut and paste from unix text.

SumoRunner
Put four spaces in the beginning of each line to preserve the formatting of code.
Jouni K. Seppänen
Why we providing 'y' and 'n' as parameters to inquire() if the case switches are hardcoded? That's just asking for misuse. They are fixed parameters, not changable, so the echo on line 2 should read: echo -n "$1 [Y/N]? "They can't be changed, so they shouldn't be supplied.
Myrddin Emrys
+30  A: 

The simplest and most widely available method to get user input at a shell prompt is the 'read' command. The best way to illustrate its use is a simple demonstration:

while true; do
    read -p "Do you wish to install this program?" yn
    case $yn in
        [Yy]* ) make install; break;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
done

Another method, pointed out by Steven Huwig, is bash's 'select' command. Here is the same example using select:

echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
    case $yn in
        Yes ) make install; break;;
        No ) exit;;
    esac
done

With select you don't need to sanitize the input... it prompts you with your choices, and you type a number corresponding to the choice you want. Select also loops automatically... there's no need for a 'while true' loop to retry if they give invalid input.

Myrddin Emrys
read -p "Do you wish to install this program? " yn...
Steve Baker
Using Bash in OS X Leopard, I changed `exit` to `break` to keep from closing the tab when I selected 'no'.
Trey Piepmeier
+1  A: 

I suggest you use dialog... it's simple and easy to use, there's also a gnome version called gdialog that takes the exact same parameters, but shows it GUI style on X.

Osama ALASSIRY
+2  A: 

Bash has select for this purpose.

select result in Yes No Cancel
do
    echo $result
done
Steven Huwig