我想暂停shell脚本中的输入,并提示用户进行选择。标准的是、否或取消类型问题。如何在典型的bash提示符中完成此操作?
当前回答
在这种情况下,我已经多次使用case语句,使用case语句是一种很好的方法。可以实现while循环,该循环模拟case块,利用布尔条件,以便更好地控制程序,并满足许多其他要求。在满足所有条件后,可以使用中断,将控制权传递回程序的主要部分。此外,为了满足其他条件,当然可以在控制结构中添加条件语句:case语句和可能的while循环。
使用案例陈述来满足您的请求的示例
#! /bin/sh
# For potential users of BSD, or other systems who do not
# have a bash binary located in /bin the script will be directed to
# a bourne-shell, e.g. /bin/sh
# NOTE: It would seem best for handling user entry errors or
# exceptions, to put the decision required by the input
# of the prompt in a case statement (case control structure),
echo Would you like us to perform the option: "(Y|N)"
read inPut
case $inPut in
# echoing a command encapsulated by
# backticks (``) executes the command
"Y") echo `Do something crazy`
;;
# depending on the scenario, execute the other option
# or leave as default
"N") echo `execute another option`
;;
esac
exit
其他回答
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
更通用的是:
function menu(){
title="Question time"
prompt="Select:"
options=("Yes" "No" "Maybe")
echo "$title"
PS3="$prompt"
select opt in "${options[@]}" "Quit/Cancel"; do
case "$REPLY" in
1 ) echo "You picked $opt which is option $REPLY";;
2 ) echo "You picked $opt which is option $REPLY";;
3 ) echo "You picked $opt which is option $REPLY";;
$(( ${#options[@]}+1 )) ) clear; echo "Goodbye!"; exit;;
*) echo "Invalid option. Try another one.";continue;;
esac
done
return
}
在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的优秀答案。
此解决方案读取单个字符,并在yes响应时调用函数。
read -p "Are you sure? (y/n) " -n 1
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
do_something
fi
用最少的行数实现这一点的最简单方法如下:
read -p "<Your Friendly Message here> : y/n/cancel" CONDITION;
if [ "$CONDITION" == "y" ]; then
# do something here!
fi
if只是一个例子:如何处理这个变量取决于您。