如何从文本文件向交互式 bash 脚本提供输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15441430/
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 to feed input to an interactive bash script from a text file
提问by etsauer
I have a script (from a vendor.. for masking passwords) that walks through a series of user inputs, and generates some output based on input. I would like to be able to wrap another script around it which feeds the input from a text file, and then captures the output for later use. Anyone have any examples of this?
我有一个脚本(来自供应商......用于屏蔽密码),它遍历一系列用户输入,并根据输入生成一些输出。我希望能够围绕它包装另一个脚本,该脚本从文本文件提供输入,然后捕获输出供以后使用。有人有这方面的例子吗?
UPDATE: I've done some digging, and it turns out the shell script is kicking off a java process which is what is requesting user input. xargs and <,>,| don't seem to work for this.
更新:我已经做了一些挖掘,结果证明 shell 脚本正在启动一个 java 进程,它是请求用户输入的。xargs 和 <,>,| 似乎不适合这个。
回答by Lorkenpeist
myscript < input_file > output_file(from the command line) will read input_fileline by line as if it were user input, and then write the output to output_file. Be careful though, if output_filealready exists, it will be completely overwritten without any warning.
myscript < input_file > output_file(从命令行)将input_file像用户输入一样逐行读取,然后将输出写入output_file. 但是要小心,如果output_file已经存在,它将在没有任何警告的情况下被完全覆盖。
回答by dronus
You could try the expectprogram that is available as package for most linux distributions. It uses a simple script language to feed interactive programs. An example script can be like this:
您可以尝试expect作为大多数 linux 发行版的软件包提供的程序。它使用简单的脚本语言来提供交互式程序。一个示例脚本可以是这样的:
#!/usr/bin/expect
spawn passwordmanager
expect "Enter password for testuser:"
send "verysecret123"
This script would tell expectto launch the program passwordmanager, then wait for the prompt Enter password for testuser:and answer it with verysecret123and so on.
这个脚本会告诉expect启动程序passwordmanager,然后等待提示Enter password for testuser:并回答它verysecret123等等。
回答by GoZoner
How about a shell function
一个shell函数怎么样
function script_plus ()
{
if [ $# != 2 ]; then echo "usage: ..."; exit; fi
src=;
tgt=;
if [ ! -f $src ]; then echo "usage: ..."; exit; fi
cat $src | xargs script > $tgt
}
Assumes 'script' is your vendor script. Does no error checking (for illustration only). If not a shell function, the body of the above script_pluscould be the content of a shell script file.
假设“脚本”是您的供应商脚本。不进行错误检查(仅用于说明)。如果不是 shell 函数,上面的主体script_plus可能是 shell 脚本文件的内容。

