Domanda

On the command line, after using diff on two files that differ, the command

echo $?   

reports back '1'. When I try the same in a script, as follows:

echo "` diff $F1 $F2`"   
rv=$?  
if [[ $rv == 1 ]]  
then    
    echo "failed"    
fi        

then I never print 'failed' (even for differing files). Note that this is the bash shell, so the grammar should be fine (eg, if I check for '0' instead, it always prints).

How can I check if the diff command discovered differences, and process conditionally on that?

This is under Ubuntu 12.04.

È stato utile?

Soluzione 4

You probably want to do this instead.

echo "`diff $F1 $F2`"
diff $F1 $F2 > /dev/null 2>&1
rv=$?
...

because $? is get set to 0 by the successful execution of echo.

And if you don't want to run diff twice you could do this too ..

   diff $F1 $F2 > /tmp/thediff 2>&1
   if [ $? != 0 ]
   then
      cat /tmp/thediff
   fi

Altri suggerimenti

You're not seeing the return value from diff because the last command run is actually echo and you're seeing its return value. You should be able to achieve the desired effect with the following code (capturing and then echoing the output of diff is unnecessary - just let it write to stdout):

diff $F1 $F2
rv=$?  
if [[ $rv == 1 ]]  
then    
    echo "failed"    
fi

Also, note that diff returns a value greater than one on error (0 indicates identical files, 1 indicates different files). You may want to check for and handle that case.

From your comment:

But I would like to print the differences first, but also keep track of how many comparisons failed.

I don't know if diff outputs the number of differences in the exit code. I think not. But you could count the lines maybe...

Here is how you can store the exit code and count the number of different lines

var=$(diff "$F1" "$F2")
#store diff exit code
exit_code=$?
# remember that this is not the same as count of differences
lines_output_by_diff=$(wc -l <<< "$var")

echo "$var"

if (($exit_code == 0)); then
  echo "same"
else
  echo "not same"
fi

It seems to be because, in your script, $? is the return status of your echo line (not the previous program), and echo will probably always work and return 0.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top