Myrddin Emrys Myrddin Emrys - 1 year ago 87
Linux Question

How do I prompt for Yes/No/Cancel input in a Linux shell script?

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 in a typical bash prompt?

Answer Source

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.";;

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;;

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.

Also, please check out the excellent answer by F. Hauri below.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download