如何在Linux shell脚本中提示Yes/No/Cancel输入

如何在Linux shell脚本中提示Yes/No/Cancel输入

问题:

我想暂停 shell 脚本中的输入,并提示用户进行选择。

标准的 Yes, No, 或 Cancel 类型问题。

如何在一个典型的 bash 提示中实现这一点?


回答:

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

bash 复制代码
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 的相同示例:

bash 复制代码
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 在她的回答中展示了一种使请求与语言无关的方法。将我的第一个示例调整以更好地服务于多种语言可能会像下面这样:

bash 复制代码
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),这需要在更完整的翻译中解决,但在许多情况下,即使是部分翻译也会有所帮助。


参考:

  • stackoverflow question 226703

相关阅读:

相关推荐
华强笔记35 分钟前
Linux内存管理系统性总结
linux·运维·网络
十五年专注C++开发1 小时前
CMake进阶: CMake Modules---简化CMake配置的利器
linux·c++·windows·cmake·自动化构建
拾心211 小时前
【运维进阶】Ansible 角色管理
运维·ansible
phoenix09812 小时前
ansible部署lnmp-allinone
linux·运维·ansible
winds~2 小时前
【git】 撤销revert一次commit中的某几个文件
linux·c++
iY_n3 小时前
Linux网络基础
linux·网络·arm开发
硅上观道3 小时前
打造 NixOS 开发环境 (1):为什么选择 Nix
linux
phoenix09813 小时前
Linux入门DAY27
linux·运维·服务器
♞沉寂5 小时前
信号以及共享内存
linux·c语言·开发语言
egoist20236 小时前
【Linux仓库】进程创建与进程终止【进程·柒】
linux·运维·服务器·进程创建·写时拷贝·进程终止