linux - [Solved-6 Solutions] How to prompt user for Yes No Cancel input in a Linux shell script - ubuntu - red hat - debian - linux server - linux pc



Linux - Problem :

How to prompt user for Yes No Cancel input in a Linux shell script ?

Linux - Solution 1:

To get user input at a shell prompt is the read command.

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
click below button to copy the code. By - Linux tutorial - team

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
click below button to copy the code. By - Linux tutorial - team

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

Linux - Solution 2:

echo "Please enter some input: "
read input_variable
echo "You entered: $input_variable"
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 3:

You can use the built-in read command. Use the -p option to prompt the user with a question.

read -e -p "Enter the path to the file: " -i "/usr/local/etc/" FILEPATH
echo $FILEPATH
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 4:

Bash has select for this purpose.

select result in Yes No Cancel
do
    echo $result
done
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 5:

read -p "Are you alright? (y/n) " RESP
if [ "$RESP" = "y" ]; then
  echo "Glad to hear it"
else
  echo "You need more bash programming"
fi
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 6:

#!/bin/sh

promptyn () {
    while true; do
        read -p "$1 " yn
        case $yn in
            [Yy]* ) return 0;;
            [Nn]* ) return 1;;
            * ) echo "Please answer yes or no.";;
        esac
    done
}

if promptyn "is the sky blue?"; then
    echo "yes"
else
    echo "no"
fi
click below button to copy the code. By - Linux tutorial - team

Related Searches to - linux - linux tutorial - How to prompt user for Yes No Cancel input in a Linux shell script