如何在 Linux shell 脚本中提示是/否/取消输入? [英] How do I prompt for Yes/No/Cancel input in a Linux shell script?

查看:40
本文介绍了如何在 Linux shell 脚本中提示是/否/取消输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 shell 脚本中暂停输入,并提示用户进行选择.
标准的YesNoCancel 类型的问题.
如何在典型的 bash 提示符下完成此操作?

I want to pause input in a shell script, and prompt the user for choices.
The standard Yes, No, or Cancel type question.
How do I accomplish this in a typical bash prompt?

推荐答案

在 shell 提示下获取用户输入的最简单和最广泛可用的方法是 read 命令.说明其使用的最佳方式是一个简单的演示:

The simplest and most widely available method to get user input at a shell prompt is the read command. 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

另一种方法,指出steven-huwig">Steven Huwig,是 Bash 的 <代码>选择命令.下面是使用 select 的相同示例:

Another method, pointed out by Steven Huwig, is Bash's select command. Here is the same example using 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 循环重试.

With select you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a while true loop to retry if they give invalid input.

此外,Léa Gris 展示了一种在 她的回答.调整我的第一个示例以更好地服务于多种语言可能如下所示:

Also, Léa Gris demonstrated a way to make the request language agnostic in her answer. 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
    if [[ "$yn" =~ $yesexpr ]]; then make install; exit; fi
    if [[ "$yn" =~ $noexpr ]]; then exit; fi
    echo "Answer ${yesword} / ${noword}."
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.

最后,请查看 优秀答案/1765658/f-hauri">F.豪里.

Finally, please check out the excellent answer by F. Hauri.

这篇关于如何在 Linux shell 脚本中提示是/否/取消输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆