【问题标题】:Shell Script: How to read standard output of a program from consoleShell 脚本:如何从控制台读取程序的标准输出
【发布时间】:2019-07-01 17:28:35
【问题描述】:

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

我使用 ./my_program arg1 arg2 在 shell 脚本上运行我的程序(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。我只想读取在控制台中编写的程序的输出。我不使用日志文件,因此不会使用在文件中搜索 (grep)。

感谢您的帮助!

【问题讨论】:

  • 你为什么不想使用expect?这正是它的目的。作业还是什么?
  • 这不是作业。据我所知,为了使用expect,我应该下载一个库。出于安全问题,禁止将任何内容下载到我正在使用的计算机上。如果期望是唯一的解决方案,那么我必须使用期望并找到使用它的方法。所以让我知道:)

标签: linux bash shell unix sh


【解决方案1】:

这是你想要做的吗?

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

如果没有,请编辑您的问题以阐明您的要求并提供更具体的示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 2020-08-24
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2014-03-17
    • 1970-01-01
    相关资源
    最近更新 更多