如何将命令(例如diff)的输出保存到变量中

我想测试diff是否有任何输出(测试文件是否相同),如果没有echo "Passed $x" else echo "Failed $x" 。 我提出了一些中间步骤(将diff的输出保存到文件然后从文件中读取)

 diff "./helloworld$x.out" "./output/helloworld$x.out" > tmp.txt; output="`cat tmp.txt`"; if [ "$output" = "" ]; then echo "Passed $x"; else echo "Failed $x"; fi; 

我确定代码可以改进吗? 主要问题是:是否可以将diff的输出直接保存到变量中?

这有效:

 如果是差异“./helloworld$x.out”“./ output / helloworld$x.out”> / dev / null; 然后
     echo“通过$ x”;
其他
     echo“Failed $ x”;
科幻

如果使用变量而不是echo ,则可以删除else分支:在if和save 2行代码之前将变量设置为false。

如果要将结果实际放入变量使用:

 some_var="$(diff "./helloworld$x.out" "./output/helloworld$x.out")" 

包括我的测试,看看它是否确实有效:

 rinzwind @ discworld:〜$ touch 1
 rinzwind @ discworld:〜$ touch 2
 rinzwind @ discworld:〜$ more test
如果diff 1 2> / dev / null; 然后
     echo“通过$ x”;
其他
     echo“Failed $ x”;
科幻
 rinzwind @ discworld:〜$ ./test
通过 

 rinzwind @ discworld:〜$ vi 2
 rinzwind @ discworld:〜$ more 2
 2
 rinzwind @ discworld:〜$ ./test
失败 

>/dev/null部分: >/dev/null 2>&1将输出发送到>/dev/null2>&1将标准错误发送到同一个文件( &1表示’使用第一个参数’)前面这个命令(所以它也使用/dev/null )。

旁注: sdiff将展示并排diff列表:

 sdiff 1 2 
 1 1
 2 2
 3 3
 4 4
 5 5
 7 7
                                   > 8
 9 9
 10 10

diff甚至可以使用下面的代码完全抑制输出,除了“Files / bin / bash和/ bin / sh different”消息。

 file1="./helloworld$x.out" file2="./output/helloworld$x.out" if diff -q "$file1" "$file2"; then echo "Passed $x" else echo "Failed $x" fi 

如果您甚至想要隐藏该消息,则必须在diff命令后附加> /dev/null以隐藏diff的输出:

 if diff -q "$file1" "$file2" >/dev/null; then 

/dev/null是一个充当黑洞的特殊文件,如果你写它,它就会消失,如果你正在读它,你将得不到任何回报。

注意bash不需要; 结束。

至于原始问题,要将程序的输出保存在变量中:

 file1="./helloworld$x.out" file2="./output/helloworld$x.out" output="$(diff -q "$file1" "$file2")" # the quotes are mandatory, this checks whether $output is empty or not if [ -n "$output" ]; then echo "Passed $x" else echo "Failed $x" fi 

检查变量是否为空的其他方法:

 [ "$output" = "" ] [ "$output" == "" ] [[ "$output" == "" ]] [[ $output == "" ]] 

如果您正在使用Bash,建议使用最后两个命令进行字符串比较。 否则,建议使用第一个和[ -n "$output" ]

a)可以使用command1的输出

 output=$(diff "helloworld$x.out" "output/helloworld$x.out") 

或者使用反叛,但是那些不鼓励,因为你不能嵌套它们,并且它们可能很难区别于萎缩,取决于字体:

  output=`cmd1` 

b)不是写入文件,然后读取该文件(或抓取输出,然后回显它),而是直接使用管道:

  cmd1 > file cat file | cmd2 output=$(cmd1) echo "${output}" | cmd2 

=>

  cmd1 | cmd2 

但在你的例子中,你对输出不感兴趣,但是程序的结果 – 它有效吗?

  diff "helloworld$x.out" "output/helloworld$x.out" && echo "success" || echo "failure" 

阅读有关&&和||的使用 搜索“快捷方式AND和快捷方式OR”。

为了保持输出清洁,您可以将’diff’的输出重定向到无处:

  diff "helloworld$x.out" "output/helloworld$x.out" >/dev/null && echo "success" || echo "failure" 

要获取成功并在以后对其进行评估,请将最后一个命令的结果存储在带有$?的变量中:

 diff "helloworld$x.out" "output/helloworld$x.out" >/dev/null result=$? # do something else case $result in 0) echo success ;; *) echo failure ;; esac 

如果你想知道两个文件是相同还是不同(但不关心实际区别是什么), cmp更合适。

 if cmp -s file1 file2; then echo "Equal"; else echo "Not equal"; fi