我想暂停shell脚本中的输入,并提示用户进行选择。标准的是、否或取消类型问题。如何在典型的bash提示符中完成此操作?
当前回答
受到@Mark和@Myrdin的回答的启发,我创建了一个通用提示的函数
uniprompt(){
while true; do
echo -e "$1\c"
read opt
array=($2)
case "${array[@]}" in *"$opt"*) eval "$3=$opt";return 0;; esac
echo -e "$opt is not a correct value\n"
done
}
这样使用:
unipromtp "Select an option: (a)-Do one (x)->Do two (f)->Do three : " "a x f" selection
echo "$selection"
其他回答
受到@Mark和@Myrdin的回答的启发,我创建了一个通用提示的函数
uniprompt(){
while true; do
echo -e "$1\c"
read opt
array=($2)
case "${array[@]}" in *"$opt"*) eval "$3=$opt";return 0;; esac
echo -e "$opt is not a correct value\n"
done
}
这样使用:
unipromtp "Select an option: (a)-Do one (x)->Do two (f)->Do three : " "a x f" selection
echo "$selection"
这是我整理的东西:
#!/bin/sh
promptyn () {
while true; do
read -p "$1 " yn
case $yn in
[Yy]* ) return 0;;
[Nn]* ) return 1;;
* ) echo "Please answer yes or no.";;
esac
done
}
if promptyn "is the sky blue?"; then
echo "yes"
else
echo "no"
fi
我是一个初学者,所以要谨慎对待,但它似乎奏效了。
一个衬垫:
read -p "Continue? [Enter] → Yes, [Ctrl]+[C] → No."
这假设“否”和“取消”具有相同的结果,因此没有理由区别对待它们。
在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的优秀答案。
read -e -p "Enter your choice: " choice
-e选项允许用户使用箭头键编辑输入。
如果要使用建议作为输入:
read -e -i "yes" -p "Enter your choice: " choice
-i选项打印提示性输入。