Shell脚本:如何从控制台读取程序的标准输出

时间:2019-07-01 17:28:35

标签: linux bash shell unix sh

我正在尝试编写一个shell脚本,该脚本向程序提供不同的输入并检查输出是否是预期的结果。在完成这些测试后,我确定可执行程序中是否存在错误。

我使用getCacheDir()通过Shell脚本运行程序(arg1和arg2是程序的命令行参数)。之后,脚本外壳会不断地向./my_program arg1 arg2提供不同的输入以对其进行测试,并在控制终端(或控制台)中反复编写标准输出,如下所示:

my_program

然后继续。对于每个输入,其输出都是已知的。因此,它们之前是匹配的。

连接失败时:写为Connection established. Intermediate result is expected_intermediate_result1 Final result is expected_result1 Connection established. Intermediate result is expected_intermediate_result2 Final result is expected_result2 否则结果可能是错误的:

Error in connection!

该脚本除了提供输入外,还有另一个目的:检查结果。

因此,我想从控制台读取输出并将它们与预期结果进行比较,以确定是否存在不一致的情况。

我需要您的帮助来编辑此代码:

Connection established.
Intermediate result is result1
Final result is wrong_result1

一些注意事项: 我不想使用while read console line-by-line if the line is other than expected result store this case to text file done 。我只想读取在控制台中编写的程序的输出。我不使用日志文件,因此不会使用文件(expect)中的搜索。

感谢您的坚持!

1 个答案:

答案 0 :(得分:1)

这是您要做什么吗?

./my_program arg1 arg2  |
grep -Fxq "Final result is expected_result1" || { printf 'Failed: "arg1 arg2" -> "expected_result1"\n'; exit 1; }

否则,请编辑您的问题以阐明您的要求并提供一个更具体的示例。