我想在 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)
yesptrn="$1"; noptrn="$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/