我想在 shell 脚本中暂停输入,并提示用户选择。
标准的 Yes
、No
或 Cancel
类型的问题。
如何在典型的 bash 提示符中完成此操作?
最佳答案
在 shell 提示符下获取用户输入的最简单和最广泛使用的方法是 read
命令。说明其用法的最佳方式是一个简单的演示:
while true; do
read -p "Do you wish to install this program? " yn
case $yn in
[Yy]* ) make install; break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
另一种方法,pointed out由 Steven Huwig , 是 Bash 的 select
命令。这是使用 select
的相同示例:
echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
case $yn in
Yes ) make install; break;;
No ) exit;;
esac
done
使用 select
您无需清理输入 - 它会显示可用选项,然后您键入与您的选择相对应的数字。它还会自动循环,因此如果 while true
循环提供无效输入,则无需重试。
另外,Léa Gris在 her answer 中演示了一种使请求语言不可知的方法.调整我的第一个示例以更好地服务于多种语言可能如下所示:
set -- $(locale LC_MESSAGES)
yesexpr="$1"; noexpr="$2"; yesword="$3"; noword="$4"
while true; do
read -p "Install (${yesword} / ${noword})? " yn
if [[ "$yn" =~ $yesexpr ]]; then make install; exit; fi
if [[ "$yn" =~ $noexpr ]]; then exit; fi
echo "Answer ${yesword} / ${noword}."
done
显然,其他通信字符串在此处仍未翻译(安装、回答),需要在更完整的翻译中解决这些问题,但在许多情况下,即使是部分翻译也会有所帮助。
最后,请查看excellent answer由 F. Hauri .
关于linux - 如何在 Linux shell 脚本中提示是/否/取消输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/226703/