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

相关阅读:

相关推荐
A小辣椒5 小时前
TShark:Wireshark CLI 功能
linux
A小辣椒9 小时前
TShark:基础知识
linux
AlfredZhao11 小时前
OCI 明明分配了 200G 系统盘,为什么 df 只看到 30G?
linux·oci
AlfredZhao1 天前
vi 删除指定范围的行,不用再反复按 dd
linux·vi
用户9718356334661 天前
银河麒麟 KY10 申威(SW64) 安装 nginx-1.16.1-2.p01.ky10.sw_64.rpm 详细步骤
linux
猪脚踏浪1 天前
linux 拷贝文件或目录到指定的位置
linux
大树882 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠2 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质2 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
bush42 天前
嵌入式linux学习记录十四、术语
linux·嵌入式