如何自动响应 Linux Bash 脚本中的提示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40791622/
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
How can I respond to prompts in a Linux Bash script automatically?
提问by Ron
I am running a script (I can't edit it), and there are three yes/no questions. How can I automatically respond to these questions? I need to answer yes, yes, no (in that order).
我正在运行一个脚本(我无法编辑它),有三个是/否问题。我如何自动回答这些问题?我需要回答是,是,否(按此顺序)。
回答by Cyrus
Try this:
尝试这个:
echo -e "yes\nyes\nno" | /path/to/your/script
From help echo
:
来自help echo
:
-e
: enable interpretation of the following backslash escapes
-e
: 启用对以下反斜杠转义的解释
回答by Todd A. Jacobs
Pipe to Standard Input
管道到标准输入
Some scripts can take replies from standard input. One of the many ways to do this would be:
一些脚本可以从标准输入中获取回复。执行此操作的众多方法之一是:
$ printf "%s\n" yes yes no | ./foo.sh
yes yes no
This is simple and easy to read, but relies on how your script internals handle standard input, and if you can't edit the target script that can sometimes be a problem.
这很简单且易于阅读,但取决于您的脚本内部处理标准输入的方式,以及如果您无法编辑有时可能会出现问题的目标脚本。
Use Expect for Interactive Prompts
使用 Expect 进行交互式提示
While you can sometimes get away with using standard input, interactive prompts are generally better handled by tools like Expect. For example, given a script foo.sh, you can write foo.expto automate it.
虽然有时您可以避免使用标准输入,但交互式提示通常由Expect 等工具处理得更好。例如,给定一个脚本foo.sh,你可以编写foo.exp来自动化它。
Note: You can also use autoexpectto create a a script from an interactive session, which you can then edit if necessary. I'd highly recommend this for people new to Expect.
注意:您还可以使用autoexpect从交互式会话创建脚本,然后您可以根据需要对其进行编辑。我强烈推荐这个给 Expect 的新手。
Bash Script: foo.sh
Bash 脚本:foo.sh
This is the script you might want to automate.
这是您可能想要自动化的脚本。
#!/usr/bin/env bash
for question in Foo Bar Baz; do
read -p "${question}? "
replies=("${replies[@]}" "$REPLY")
done
echo "${replies[@]}"
Expect Script: foo.exp
预期脚本:foo.exp
Here is a simplistic Expect script to automate the Bash script above. Expect loops, branching, and regular expressions can provide much more flexibility than this oversimplified example shows, but it doesshow how easy a minimal Expect script can be!
这是一个简单的 Expect 脚本,用于自动化上面的 Bash 脚本。Expect 循环、分支和正则表达式可以提供比这个过于简化的示例显示的更大的灵活性,但它确实展示了一个最小的 Expect 脚本是多么容易!
#!/usr/bin/env expect
spawn -noecho /tmp/foo.sh
expect "Foo? " { send -- "1\r" }
expect "Bar? " { send -- "2\r" }
expect "Baz? " { send -- "3\r" }
interact
Sample Interactive Session
示例交互式会话
This is what your interactive session will look like when you run the Expect script. It will spawn your Bash script, and respond as instructed to each different prompt.
这就是运行 Expect 脚本时交互式会话的样子。它将生成您的 Bash 脚本,并按照指示响应每个不同的提示。
$ /tmp/foo.exp
Foo? 1
Bar? 2
Baz? 3
1 2 3