如何在bash中提示是或否?

时间:2015-04-03 16:45:40

标签: bash shell unix command-line sh

如何在Bash中询问是/否类型的问题?

我问的问题是...... echo "Do you like pie?"

并得到答案...... read pie

如果答案是yes,或者以y开头,我该怎么办?(是的,是的,等等,也会有效)。

5 个答案:

答案 0 :(得分:9)

我喜欢使用以下功能:

function yes_or_no {
    while true; do
        read -p "$* [y/n]: " yn
        case $yn in
            [Yy]*) return 0  ;;  
            [Nn]*) echo "Aborted" ; return  1 ;;
        esac
    done
}

因此,在您的脚本中,您可以这样使用:

yes_or_no "$message" && do_something

如果用户按下[yYnN]以外的任何键,它将重复该消息。

答案 1 :(得分:6)

这也有效:

read -e -p "Do you like pie? " choice
[[ "$choice" == [Yy]* ]] && echo "doing something" || echo "that was a no"

以Y或y开头的模式将被视为yes

答案 2 :(得分:2)

这有效:

echo "Do you like pie?"
read pie
if [[ $pie == y* ]]; then
    echo "You do! Awesome."
else
    echo "I don't like it much, either."
fi
用于查看变量[[ $pie == y* ]]

$pie测试以y开头。

如果您愿意,请随意改善。

答案 3 :(得分:0)

与其他答案相比,此功能可让您设置默认值:

function askYesNo {
        QUESTION=$1
        DEFAULT=$2
        if [ "$DEFAULT" = true ]; then
                OPTIONS="[Y/n]"
                DEFAULT="y"
            else
                OPTIONS="[y/N]"
                DEFAULT="n"
        fi
        read -p "$QUESTION $OPTIONS " -n 1 -s -r INPUT
        INPUT=${INPUT:-${DEFAULT}}
        echo ${INPUT}
        if [[ "$INPUT" =~ ^[yY]$ ]]; then
            ANSWER=true
        else
            ANSWER=false
        fi
}

askYesNo "Do it?" true
DOIT=$ANSWER

if [ "$DOIT" = true ]; then
    < do some stuff >
fi

在命令行上,您会看到

Do it? [Y/n] y

答案 4 :(得分:0)

我喜欢Jahid's oneliner。以下是对它的略微简化:

[[ "$(read -e -p 'Continue? [y/N]> '; echo $REPLY)" == [Yy]* ]]

以下是一些测试:

$ [[ "$(read -e -p 'Continue? [y/N]> '; echo $REPLY)" == [Yy]* ]] && echo Continuing || echo Stopping

Continue? [y/N]> yes
Continuing

$ for test_string in y Y yes YES no ''; do echo "Test String: '$test_string'"; echo $test_string | [[ "$(read -e -p 'Continue? [y/N]>'; echo $REPLY)" == [Yy]* ]] && echo Continuing || echo Stopping; done

Test String: 'y'
Continuing

Test String: 'Y'
Continuing

Test String: 'yes'
Continuing

Test String: 'YES'
Continuing

Test String: 'no'
Stopping

Test String: ''
Stopping