bash 以非交互方式将参数传递给交互式程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14392525/
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
Passing arguments to an interactive program non-interactively
提问by sidharth sharma
I have a bash script that employs the read
command to read arguments to commands interactively, for example yes/no options. Is there a way to call this script in a non-interactive script passing default option values as arguments?
我有一个 bash 脚本,它使用read
命令以交互方式读取命令的参数,例如是/否选项。有没有办法在传递默认选项值作为参数的非交互式脚本中调用这个脚本?
It's not just one option that I have to pass to the interactive script.
这不仅仅是我必须传递给交互式脚本的一种选择。
采纳答案by Dani Gehtdichnixan
For more complex tasks there is expect
( http://en.wikipedia.org/wiki/Expect).
It basically simulates a user, you can code a script how to react to specific program outputs and related stuff.
对于更复杂的任务,有expect
(http://en.wikipedia.org/wiki/Expect)。它基本上模拟用户,您可以编写脚本如何对特定程序输出和相关内容做出反应。
This also works in cases like ssh
that prohibits piping passwords to it.
这也适用于ssh
禁止将密码传递给它的情况。
回答by glenn Hymanman
Many ways
很多方法
pipe your input
管道输入
echo "yes
no
maybe" | your_program
redirect from a file
从文件重定向
your_program < answers.txt
use a here document(this can be very readable)
使用here 文档(这可能非常易读)
your_program << ANSWERS
yes
no
maybe
ANSWERS
use a here string
使用这里字符串
your_program <<< $'yes\nno\nmaybe\n'
回答by Guru
You can put the data in a file and re-direct it like this:
您可以将数据放在一个文件中并像这样重定向它:
$ cat file.sh
#!/bin/bash
read x
read y
echo $x
echo $y
Data for the script:
脚本数据:
$ cat data.txt
2
3
Executing the script:
执行脚本:
$ file.sh < data.txt
2
3
回答by Guru
Just want to add one more way. Found it elsewhere, and is quite simple. Say I want to pass yes for all the prompts at command line for a command "execute_command", Then I would simply pipe yes to it.
只是想增加一种方式。在别处找到的,很简单。假设我想为命令“execute_command”的命令行中的所有提示传递yes,然后我只需将yes传递给它。
yes | execute_command
This will use yes as the answer to all yes/no prompts.
这将使用 yes 作为所有是/否提示的答案。