我编写的 shell 脚本的可用性测试发现,人们对于如何回答期望答案为“是”的问题有不同的期望。请参阅以下代码示例中的变体。
当然一定有比我想出的更好的方法吗?你的...是可读的和较短的形式接受这个吗?
read -p 'Answer this question with yes: ' answer
if [ "$answer" = 'Y'
-o "$answer" = 'YES'
-o "$answer" = 'Yes'
-o "$answer" = 'y'
-o "$answer" = 'yes'
-o some-alternate-condition ]; then
echo 'Surely this can be written better?'
fi
答案1
UNIX 标准为此提供了示例代码,使用locale
公用事业:
if printf "%s\n" "$response" | grep -Eq "$(locale yesexpr)"
then
affirmative processing goes here
else
non-affirmative processing goes here
fi
POSIX
语言环境中(以及真实系统上的英语语言环境)中“yesexpr”的值为"^[yY]"
。它被解释为扩展的正则表达式。另请参见 noexpr。
答案2
使用 acase
在某种程度上是等效的,但并不完美,因为类似的语句YE
被接受。
read -p 'Answer this question with yes: ' answer
case "${answer}" in
[yY]|[yY][eE][sS])
echo 'Surely this can be written better?' ;;
esac
答案3
留在 bash(或任何其他 shell,如果您独立显示提示符):
case $answer in
[Yy]*) echo Ok;;
*) echo "Can't you read? I said to say yes.";;
esac
它接受诸如yn
“是”、 y
(带有初始空格)“否”和wlkjzuhfod
“否”之类的响应,这可能不是最佳的,但与典型的 shell 提示一致:这就是rm -i
和find -ok
其他人的做法。
这避开了国际化的整个问题:在其他语言中,您需要翻译预期的响应。那么就没有标准的 shell 方法;你可以转向对话,但是您的脚本将要求安装它(它在许多发行版中可用,但默认情况下并不总是安装)。
if dialog --yesno "Choose yes" 0 0; then …
答案4
刚刚重新修改了@faif ans
YesOrNo() {
while :
do
read -p 'Do you want to Continue (yes/no?): ' answer
case "${answer}" in
[yY]|[yY][eE][sS]) exit 0 ;;
[nN]|[nN][oO]) exit 1 ;;
esac
done
}
if $( YesOrNo ); then
echo "Ans is yes.. Do something....."
else
echo "Ans is No... skip.."
fi
测试
root@ubuntu:~# bash confirm.sh
Do you want to Continue (yes/no?): # if Blank Enter then ask again
Do you want to Continue (yes/no?):
Do you want to Continue (yes/no?):
Do you want to Continue (yes/no?): no
Ans is No... skip..
root@ubuntu:~# bash confirm.sh
Do you want to Continue (yes/no?):
Do you want to Continue (yes/no?):
Do you want to Continue (yes/no?): ye
Do you want to Continue (yes/no?): yes
Ans is yes.. Do something.....