Bash 脚本知道命令的结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2935663/
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
Bash scripting know the result of a command
提问by Tiago Veloso
I am writing a bash script to run an integration test of a tool I am writing.
我正在编写一个 bash 脚本来运行我正在编写的工具的集成测试。
Basically I run the application with a set of inputs and compare the results with expected values using the diff command line tool.
基本上,我使用一组输入运行应用程序,并使用 diff 命令行工具将结果与预期值进行比较。
It's working, but I would like to enhance it by knowing the result of the diff command and print "SUCCESS" or "FAIL" depending on the result of the diff.
它正在工作,但我想通过了解 diff 命令的结果并根据 diff 的结果打印“成功”或“失败”来增强它。
How can I do it?
我该怎么做?
回答by exic
if diff file1 file2; then
echo Success
else
echo Fail
fi
If both files are equal, diff returns 0, which is the return code for ifto follow then. If file1 and file2 differ, diff returns 1, which makes if jump to the elsepart of the construct.
如果两个文件相等,则 diff 返回 0,这是ifto follow的返回码then。如果 file1 和 file2 不同,则 diff 返回 1,这使得 if 跳转到else构造的部分。
You might want to suppress the output of diff by writing diff file1 file2 >/dev/nullinstead of the above.
您可能希望通过写入diff file1 file2 >/dev/null而不是上述内容来抑制 diff 的输出。
回答by Igor
The $?variable holds the result of the last executed command.
该$?变量保存上次执行命令的结果。
回答by Paused until further notice.
Also, in Bash you can diffthe outputs of commands directly using process substitution:
此外,在 Bash 中,您可以diff使用进程替换直接输出命令:
if diff <(some_command arg1) <(some_command arg1) > /dev/null 2>&1
then
echo "They're the same."
else
echo "They're different."
fi

