如何在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

相关阅读:

相关推荐
无足鸟ICT3 小时前
【RHCA+】_proc_pid_cmdline
linux·运维·服务器
学以智用4 小时前
CentOS Linux 文件操作详解
linux
饿了吃洗衣凝珠5 小时前
shell循环
linux·运维·服务器
代码不停6 小时前
Linux基础知识
java·linux·数据库
木雷坞6 小时前
Docker 镜像源列表(11月30日更新-长期)
运维·docker·容器
东风微鸣6 小时前
Linux台式机也能指纹识别登录验证啦
linux·指纹
迪康软件zz8 小时前
单向阀的代码:把"高级别解低级别"写成可测的判定
运维·安全·自动化运维
Diligently_8 小时前
docker 中的常见的使用命令(三)
运维·docker·容器
路溪非溪8 小时前
USB的基础知识总结
linux
女神下凡8 小时前
芯易选(143):晶视智能(CVITEK)_开发指南
linux·arm开发·stm32·单片机·嵌入式硬件