Dan*_*iel 27 bash prompt shell-script
我编写的一个 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
Run Code Online (Sandbox Code Playgroud)
Ran*_*832 49
UNIX 标准为此使用locale实用程序提供了示例代码:
if printf "%s\n" "$response" | grep -Eq "$(locale yesexpr)"
then
affirmative processing goes here
else
non-affirmative processing goes here
fi
Run Code Online (Sandbox Code Playgroud)
'yesexpr' 在POSIX语言环境(以及真实系统上的英语语言环境)中的值为"^[yY]". 它被解释为扩展的正则表达式。另见 noexpr。
sak*_*isk 15
使用 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
Run Code Online (Sandbox Code Playgroud)
留在 bash (或任何其他 shell,如果您独立显示提示):
case $answer in
[Yy]*) echo Ok;;
*) echo "Can't you read? I said to say yes.";;
esac
Run Code Online (Sandbox Code Playgroud)
这接受像ynyes、 y(带有初始空格)、no 和wlkjzuhfodno 之类的响应,这可能不是最佳的,但与典型的 shell 提示一致:这就是rm -i,find -ok其他人就是这样做的。
这避免了国际化的整个问题:在其他语言中,您需要翻译预期的响应。那时没有标准的 shell 方法;您可以转向dialog,但随后您的脚本将要求安装它(它在许多发行版中可用,但并非总是默认安装)。
if dialog --yesno "Choose yes" 0 0; then …
Run Code Online (Sandbox Code Playgroud)