The simplest and most widely available method to get user input at a shell prompt is the read
command.
(在shell提示符下获取用户输入的最简单,最广泛使用的方法是read
命令。)
The best way to illustrate its use is a simple demonstration: (演示其用法的最佳方法是一个简单的演示:)
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
Another method, pointed out by Steven Huwig , is Bash's select
command.
(Steven Huwig 指出的另一种方法是Bash的select
命令。)
Here is the same example using 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
With select
you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice.
(使用select
您不需要清理输入-它显示可用的选项,然后键入与您的选择相对应的数字。)
It also loops automatically, so there's no need for a while true
loop to retry if they give invalid input. (它还会自动循环,因此如果它们提供了无效的输入,则无需再进行一次while true
循环重试。)
Also, Léa Gris demonstrated a way to make the request language agnostic in her answer .
(此外, LEA格里斯表现出一种方法,使在请求语言无关她的回答 。)
Adapting my first example to better serve multiple languages might look like this: (修改我的第一个示例以更好地服务于多种语言可能看起来像这样:)
set -- $(locale LC_MESSAGES)
yesptrn="$1"; noptrn="$2"; yesword="$3"; noword="$4"
while true; do
read -p "Install (${yesword} / ${noword})? " yn
case $yn in
${yesptrn##^} ) make install; break;;
${noptrn##^} ) exit;;
* ) echo "Answer ${yesword} / ${noword}.";;
esac
done
Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.
(显然,这里没有翻译其他通信字符串(安装,回答),这需要通过更完整的翻译来解决,但是在许多情况下,即使是部分翻译也将有所帮助。)
Finally, please check out the excellent answer by F. Hauri .
(最后,请查看F. Hauri的出色回答 。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…