bash 如何在bash中提示是或否?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29436275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to prompt for yes or no in bash?
提问by Ben Aubin
How do I ask a yes/no type question in Bash?
如何在 Bash 中提出是/否类型的问题?
I ask the question... echo "Do you like pie?"
我问这个问题... echo "Do you like pie?"
And receive the answer... read pie
并收到答案... read pie
How do I do something if the answer is yes
, or starts with y
(so yes and yeah, etc, will work too).
如果答案是yes
,或以y
(所以是的,是的,等等,也可以),我该怎么做。
回答by Tiago Lopo
I like to use the following function:
我喜欢使用以下功能:
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
}
So in your script you can use like this:
所以在你的脚本中你可以这样使用:
yes_or_no "$message" && do_something
In case the user presses any key other than [yYnN] it will repeat the message.
如果用户按下 [yYnN] 以外的任何键,它将重复该消息。
回答by Jahid
This works too:
这也有效:
read -e -p "Do you like pie? " choice
[[ "$choice" == [Yy]* ]] && echo "doing something" || echo "that was a no"
Pattern starting with Y or y will be taken as yes
.
以 Y 或 y 开头的模式将被视为yes
。
回答by Bruno Bronosky
I like Jahid's oneliner. Here is a slight simplification of it:
我喜欢Jahid 的 oneliner。这是它的一个轻微简化:
[[ "$(read -e -p 'Continue? [y/N]> '; echo $REPLY)" == [Yy]* ]]
Here are some tests:
以下是一些测试:
$ [[ "$(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
回答by Ben Aubin
This works:
这有效:
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* ]]
tests to see of the variable $pie
starts with y.
[[ $pie == y* ]]
测试以查看变量$pie
以 y 开头。
Feel free to make this better if you'd like.
如果您愿意,请随意将其做得更好。
回答by NaN
In contrast to the other answers this function gives you the possibility to set a default:
与其他答案相比,此功能使您可以设置默认值:
function askYesNo {
QUESTION=
DEFAULT=
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
On the command line you would see
在命令行上你会看到
Do it? [Y/n] y