我想暂停 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
另一种方法是 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
它还会自动循环,因此如果它们提供无效输入,则无需循环重试。
此外,演示了一种使请求语言不可知的方法。调整我的第一个示例以更好地服务于多种语言可能如下所示:
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
显然,其他通信字符串在此处仍未翻译(安装、回答),这需要在更完整的翻译中解决,但在许多情况下,即使是部分翻译也会有所帮助。