小编典典

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

linux

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


阅读 1081

收藏
2020-06-02

共1个答案

小编典典

该命令是在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

史蒂芬·休伊格(StevenHuwig)指出的另一种方法是Bash的命令。这是使用的相同示例:selectselect

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如果输入无效,则无需重试循环。

此外,LEA格里斯表现出一种方法,使在请求语言无关她的回答。修改我的第一个示例以更好地服务于多种语言可能看起来像这样:

set -- $(locale LC_MESSAGES)
yesptrn="$1"; noptrn="$2"; yesword="$3"; noword="$4"

while true; do
    read -p "Install (${yesword} / ${noword})? " yn
    case $yn in
        ${yesptrn##^} ) make install; break;;
        ${noptrn##^} ) exit;;
        * ) echo "Answer ${yesword} / ${noword}.";;
    esac
done

显然,这里没有翻译其他通信字符串(安装,回答),这需要通过更完整的翻译来解决,但是在许多情况下,即使是部分翻译也将有所帮助。

2020-06-02