我想暂停shell脚本中的输入,并提示用户进行选择。标准的是、否或取消类型问题。如何在典型的bash提示符中完成此操作?
当前回答
一个衬垫:
read -p "Continue? [Enter] → Yes, [Ctrl]+[C] → No."
这假设“否”和“取消”具有相同的结果,因此没有理由区别对待它们。
其他回答
此解决方案读取单个字符,并在yes响应时调用函数。
read -p "Are you sure? (y/n) " -n 1
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
do_something
fi
read -p "Are you alright? (y/n) " RESP
if [ "$RESP" = "y" ]; then
echo "Glad to hear it"
else
echo "You need more bash programming"
fi
在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
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在她的回答中展示了一种使请求语言不可知的方法。调整我的第一个示例以更好地服务于多种语言可能如下所示:
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
显然,其他通信字符串在这里仍然没有翻译(Install,Answer),这需要在更完整的翻译中解决,但在许多情况下,即使是部分翻译也会很有用。
最后,请查看F.Hauri的优秀答案。
是/否/取消
作用
#!/usr/bin/env bash
@confirm() {
local message="$*"
local result=''
echo -n "> $message (Yes/No/Cancel) " >&2
while [ -z "$result" ] ; do
read -s -n 1 choice
case "$choice" in
y|Y ) result='Y' ;;
n|N ) result='N' ;;
c|C ) result='C' ;;
esac
done
echo $result
}
用法
case $(@confirm 'Confirm?') in
Y ) echo "Yes" ;;
N ) echo "No" ;;
C ) echo "Cancel" ;;
esac
使用干净的用户输入进行确认
作用
#!/usr/bin/env bash
@confirm() {
local message="$*"
local result=3
echo -n "> $message (y/n) " >&2
while [[ $result -gt 1 ]] ; do
read -s -n 1 choice
case "$choice" in
y|Y ) result=0 ;;
n|N ) result=1 ;;
esac
done
return $result
}
用法
if @confirm 'Confirm?' ; then
echo "Yes"
else
echo "No"
fi
您可以编写一个函数来测试:
confirm() {
local ans IFS=;
while read -rp "$1" -n1 ans;
do printf '\n';
case $ans in [Yy]) return 0;;
[Nn]) return 1;;
esac;
done;
}; ## Usage: if confirm "Are you sure? "; then ...
if confirm "Does everything look ok...reboot now? [Y/n]"; then
echo "rebooting..."
sleep 5
reboot
fi