Home > Enterprise >  How to check if a diff command is successful in Unix she'll script
How to check if a diff command is successful in Unix she'll script

Time:07-24

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

CodePudding user response:

Just check diff.

if diff s1 d1 ; then
   echo "checksums match"
else
   echo "checksums do not match"
fi

If you don't want to have output on terminal, you would use cmp.

if cmp -s s1 d2 ; then ...

CodePudding user response:

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.)

  • Related