如果你可以使用bash,并且 - 例如 - 你的程序输出的每一行输入一条线,那么所有你需要从你的shell脚本做的是:
- 存储您的输入。
- 将它传递给你的程序并存储输出。
- 交替地回显每条输入和输出线。
以下是一个C程序,这只是呼应输入给它的任何线,以“您输入”前缀:
#include <stdio.h>
int main(void){
char buffer[1024];
while (fgets(buffer, 1024, stdin)) {
printf("You entered: %s", buffer);
}
return 0;
}
如果我们从终端运行,如果,我们得到这样的:
[email protected]:~/src/sandbox$ ./sample
first line
You entered: first line
second line
You entered: second line
third line
You entered: third line
[email protected]:~/src/sandbox$
(使用CTRL-D在输入第三行后终止输入)。
这里有一个bash脚本来模拟:
#!/bin/bash
# Pass input to program and store output
input=$'first line\nsecond line\nthird line'
output=`echo "$input" | ./sample`
# Split input and output lines to arrays
IFS=$'\n'
inlines=($input)
outlines=($output)
# Alternately print input and outline lines
for i in "${!inlines[@]}"; do
echo "${inlines[$i]}"
echo "${outlines[$i]}"
done
这给输出:
[email protected]:~/src/sandbox$ ./test_sample.sh
first line
You entered: first line
second line
You entered: second line
third line
You entered: third line
[email protected]:~/src/sandbox$
它等同于它的外观在交互式会话。
如果你的程序没有使用像这样的简单的逐行呼叫和响应,那么你将有更多的工作要做,但如果你有所有的输入和输出线路,而你知道该期待什么,那么这是可行的,因为在程序结束后,您仍然可以访问所有输入和所有输出,并且可以根据需要回显它们。
您是否考虑过使用['expect'](http://en.wikipedia.org/wiki/Expect)(或['pexpect'](https://github.com/pexpect/pexpect)) ? – John1024 2014-10-20 02:50:06
我有,但正如我之前提到的,我不能使用任何工具,因为我非常怀疑分级的人会期望什么或者已经安装了哪些工具。 – user1356809 2014-10-20 03:21:53
.sh将与我们在大学使用的所有Linux计算机一起使用,以便我可以安全地使用它。 – user1356809 2014-10-20 03:22:34