如何在bash中提示是或否?

Ben*_*bin 7 unix bash shell command-line sh

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

我问这个问题...... echo "Do you like pie?"

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

如果答案是yes或开始,我该怎么办?y(是的,是的,等等,也会起作用).

Tia*_*opo 10

我喜欢使用以下功能:

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
}
Run Code Online (Sandbox Code Playgroud)

所以在你的脚本中你可以像这样使用:

yes_or_no "$message" && do_something
Run Code Online (Sandbox Code Playgroud)

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

  • `read -p "$@ [y/n]: "` 不正确,您需要使用 `$*` ,否则如果使用多个参数调用该函数,读取将会爆炸。另外,从技术上讲,这应该使用`yes_or_not "$@"`,但只有当您使用`yes_or_not 'foo bar'`并且用户不输入是或否时才重要(内部空格将丢失)。 (2认同)

Ben*_*bin 6

这有效:

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
Run Code Online (Sandbox Code Playgroud)

[[ $pie == y* ]]测试以 y 开头的变量$pie

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


Jah*_*hid 6

这也有效:

read -e -p "Do you like pie? " choice
[[ "$choice" == [Yy]* ]] && echo "doing something" || echo "that was a no"
Run Code Online (Sandbox Code Playgroud)

以Y或y开头的图案将被视为yes.

  • 很棒的1班轮 (2认同)

Bru*_*sky 6

我喜欢Jahid 的 oneliner。这是它的一个轻微简化:

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

以下是一些测试:

$ [[ "$(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
Run Code Online (Sandbox Code Playgroud)

  • @Akhil 我为你添加了一个“zsh”示例。☮️❤️ (3认同)