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

相关阅读:

相关推荐
whgjjim27 分钟前
docker迅雷自定义端口号、登录用户名密码
运维·docker·容器
tmacfrank1 小时前
网络编程中的直接内存与零拷贝
java·linux·网络
瀚高PG实验室4 小时前
连接指定数据库时提示not currently accepting connections
运维·数据库
QQ2740287564 小时前
Soundness Gitpod 部署教程
linux·运维·服务器·前端·chrome·web3
淡忘_cx4 小时前
【frp XTCP 穿透配置教程
运维
qwfys2004 小时前
How to configure Linux mint desktop
linux·desktop·configure·mint
南方以南_4 小时前
Ubuntu操作合集
linux·运维·ubuntu
冼紫菜5 小时前
[特殊字符]CentOS 7.6 安装 JDK 11(适配国内服务器环境)
java·linux·服务器·后端·centos
Chuncheng's blog6 小时前
RedHat7 如何更换yum镜像源
linux
爱莉希雅&&&6 小时前
shell脚本之条件判断,循环控制,exit详解
linux·运维·服务器·ssh