Saturday, May 4, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  20] [ 0]  / answers: 1 / hits: 49492  / 2 Years ago, fri, february 25, 2022, 2:29:50

I want to test if there is any output from the diff (test if files are same), if none echo "Passed $x" else echo "Failed $x". I came up with some intermidiate step (save the output from diff to a file then read from file)



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;


I'm sure the code can be improved? Main question is: is it possible to save the output from diff directly into a variable?


More From » bash

 Answers
6

This works:



if diff "./helloworld$x.out" "./output/helloworld$x.out" >/dev/null; then
echo "Passed $x";
else
echo "Failed $x";
fi


If you use a variable instead of echo you could drop the else branche: set the variable to false before the if and save 2 lines of code.



If you want to actually put the result into a variable use:



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


Including my test to see if it does actually work:




rinzwind@discworld:~$ touch 1
rinzwind@discworld:~$ touch 2
rinzwind@discworld:~$ more test
if diff 1 2 >/dev/null; then
echo "Passed $x";
else
echo "Failed $x";
fi
rinzwind@discworld:~$ ./test
Passed

rinzwind@discworld:~$ vi 2
rinzwind@discworld:~$ more 2
2
rinzwind@discworld:~$ ./test
Failed


On the >/dev/null part: >/dev/null 2>&1 will send output to >/dev/null and 2>&1 will send standard errors to the same file (&1 means 'use first parameter') in front of this command (so it also uses /dev/null).



sidenote: sdiff will show a side-by-side diff listings:




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

[#43880] Sunday, February 27, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
inciplyies

Total Points: 10
Total Questions: 114
Total Answers: 93

Location: French Polynesia
Member since Sun, Dec 20, 2020
3 Years ago
;