Search code examples
shellif-statementunixdiffchecksum

How to check if a diff command is successful in Unix shell script


In a Unix shell script, I want to check if the output of a diff command is equal to 0 through an if statement. So that I can accordingly give the if case statements.

For example: Abc.sh

#!/bin/bash
cd users
diff s1 d1 > a.txt
wc -l a.txt | awk '{print f1}' > a
echo "value of a is"
cat a
if [ $a == 0 ]
  then
echo "checksums match"
  else
echo "checksums do not match"
fi

Output:

value of a is
0
[: ==: unary operator expected
checksums do not match

Solution

  • There are many ways to fix your script, but this is probably the most minimal:

    a=$(cat a)
    if [ "$a" = "" ]; then
    
    1. Variables are different from files, so you have to read the output of the file you created.
    2. Variables that potentially contain spaces must be quoted when used as arguments, and strings must be compared against empty rather than 0.

    (As suggested in the comment, if you don't need the diff output, you could just use the exit code.)