linux - 如何在 Linux shell 脚本中提示是/否/取消输入?

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

最佳答案

在 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

另一种方法,pointed out由 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在 her answer 中演示了一种使请求语言不可知的方法.调整我的第一个示例以更好地服务于多种语言可能如下所示:

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

显然,其他通信字符串在此处仍未翻译(安装、回答),需要在更完整的翻译中解决这些问题,但在许多情况下,即使是部分翻译也会有所帮助。

最后,请查看excellent answer由 F. Hauri .

https://stackoverflow.com/questions/226703/

相关文章:

python - 网址在 Python 中解码 UTF-8

linux - 如何将包含文件的文件夹复制到 Unix/Linux 中的另一个文件夹?

linux - 使用 `find` 时如何排除目录?

python - 用一个空格替换非 ASCII 字符

linux - 删除目录的符号链接(symbolic link)

python - 如果键存在,则删除字典项

linux - 在 Bash 中循环文件的内容

python - pip 在哪里安装它的包?

python - 子进程中 'shell=True'的实际含义

python - 如何禁用 Pylint 警告?