如何在 Linux shell 脚本中提示是/否/取消输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/226703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:38:21  来源:igfitidea点击:

How do I prompt for Yes/No/Cancel input in a Linux shell script?

linuxbashshellscripting

提问by Myrddin Emrys

I want to pause input in a shell script, and prompt the user for choices.
The standard Yes, No, or Canceltype question.
How do I accomplish this in a typical bash prompt?

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

采纳答案by Myrddin Emrys

The simplest and most widely available method to get user input at a shell prompt is the readcommand. The best way to illustrate its use is a simple demonstration:

在 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

Another method, pointed outby Steven Huwig, is Bash's selectcommand. Here is the same example using select:

另一种方法,指出了史蒂芬Huwig,是bash的select命令。这是使用 的相同示例select

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

With selectyou don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a while trueloop to retry if they give invalid input.

随着select你并不需要净化输入-它显示可用的选项,你键入相应的你的选择一个号码。它还会自动循环,因此while true如果它们提供无效输入,则无需循环重试。

Also, Léa Grisdemonstrated a way to make the request language agnostic in her answer. Adapting my first example to better serve multiple languages might look like this:

此外,Léa Gris她的回答中展示了一种使请求语言不可知的方法。调整我的第一个示例以更好地服务于多种语言可能如下所示:

set -- $(locale LC_MESSAGES)
yesptrn=""; noptrn=""; yesword=""; noword=""

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

Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.

显然,其他通信字符串在此处仍未翻译(安装、回答),这需要在更完整的翻译中解决,但在许多情况下,即使是部分翻译也会有所帮助。

Finally, please check out the excellent answerby F. Hauri.

最后,请检查出的出色答卷F. Hauri

回答by Pistos

echo "Please enter some input: "
read input_variable
echo "You entered: $input_variable"

回答by SumoRunner

inquire ()  {
  echo  -n " [y/n]? "
  read answer
  finish="-1"
  while [ "$finish" = '-1' ]
  do
    finish="1"
    if [ "$answer" = '' ];
    then
      answer=""
    else
      case $answer in
        y | Y | yes | YES ) answer="y";;
        n | N | no | NO ) answer="n";;
        *) finish="-1";
           echo -n 'Invalid response -- please reenter:';
           read answer;;
       esac
    fi
  done
}

... other stuff

inquire "Install now?"

...

回答by Osama Al-Maadeed

I suggest you use dialog...

我建议你使用对话框...

Linux Apprentice: Improve Bash Shell Scripts Using Dialog

The dialog command enables the use of window boxes in shell scripts to make their use more interactive.

Linux 学徒:使用对话框改进 Bash Shell 脚本

dialog 命令允许在 shell 脚本中使用窗口框,以使其使用更具交互性。

it's simple and easy to use, there's also a gnome version called gdialog that takes the exact same parameters, but shows it GUI style on X.

它简单易用,还有一个名为 gdialog 的 gnome 版本,它采用完全相同的参数,但在 X 上显示 GUI 样式。

回答by Steven Huwig

Bash has selectfor this purpose.

为此,Bash 有选择

select result in Yes No Cancel
do
    echo $result
done

回答by serg

read -p "Are you alright? (y/n) " RESP
if [ "$RESP" = "y" ]; then
  echo "Glad to hear it"
else
  echo "You need more bash programming"
fi

回答by yPhil

You can use the built-in readcommand ; Use the -poption to prompt the user with a question.

您可以使用内置的读取命令;使用该-p选项来提示用户一个问题。

Since BASH4, you can now use -ito suggest an answer :

从 BASH4 开始,您现在可以使用-i来建议答案:

read -e -p "Enter the path to the file: " -i "/usr/local/etc/" FILEPATH
echo $FILEPATH

(But remember to use the "readline" option -eto allow line editing with arrow keys)

(但请记住使用“readline”选项-e以允许使用箭头键进行行编辑)

If you want a "yes / no" logic, you can do something like this:

如果您想要“是/否”逻辑,您可以执行以下操作:

read -e -p "
List the content of your home dir ? [Y/n] " YN

[[ $YN == "y" || $YN == "Y" || $YN == "" ]] && ls -la ~/

回答by ThatLinuxGuy

Use the readcommand:

使用read命令:

echo Would you like to install? "(Y or N)"

read x

# now check if $x is "y"
if [ "$x" = "y" ]; then
    # do something here!
fi

and then all of the other stuff you need

然后你需要的所有其他东西

回答by mpen

Here's something I put together:

这是我整理的一些东西:

#!/bin/sh

promptyn () {
    while true; do
        read -p " " yn
        case $yn in
            [Yy]* ) return 0;;
            [Nn]* ) return 1;;
            * ) echo "Please answer yes or no.";;
        esac
    done
}

if promptyn "is the sky blue?"; then
    echo "yes"
else
    echo "no"
fi

I'm a beginner, so take this with a grain of salt, but it seems to work.

我是初学者,所以请谨慎对待,但它似乎有效。

回答by jlettvin

yn() {
  if [[ 'y' == `read -s -n 1 -p "[y/n]: " Y; echo $Y` ]];
  then eval ;
  else eval ;
  fi }
yn 'echo yes' 'echo no'
yn 'echo absent no function works too!'