Linux – How to check for a string match AND an empty file in the same if/then bash script statement

bashlinuxscripting

I'm writing a simple bash script to do the following:

1) Check two files (foo1 and foo2).

2) If foo1 is different from foo2 and foo1 NOT blank, send an email.

3) If foo1 is the same as foo2… or foo1 is blank… do nothing.

The blank condition is what's confusing me. Here's what I've got to start with:

diff --brief <(sort ./foo1) <(sort ./foo2) >/dev/null
comp_value=$?

if [ $comp_value -ne 0 ]
then
        mail -s "Alert" bob@bob.com <./alertfoo

fi

Obviously this doesn't check for blank contents. Any thoughts on how to do that?

Best Answer

You can use the test's -s operator to check whether the file is empty, and cmp is generally the simplest way to check files for equality (note that you can use a command directly in an if statement as a simpler alternative to comparing its exit status with 0). I'm keeping the bit where you sort the two files before comparing them; if that's not needed, just use the two files directly as arguments to cmp.

if [ -s ./foo1 ] && ! cmp -q <(sort ./foo1) <(sort ./foo2); then
    ...

You can read the above as: "if ./foo1 is not empty ([ -s ... ]) AND (&&) the sorted forms of ./foo1 and ./foo2 are NOT (!) the same (cmp)".