Help comparing 2 files and sending differences

I have 2 files that need to be compared. Email the differences if something is different and don't email if nothing is different. One or both of the files could be empty. One or both could have data in them.

example files
backup.doc.$(date +%y%m%d) file size is 0
backup.doc.$(TZ=CST+24 date +%y%m%d) file size is 412

or vice versa

Any help would be appreciated. I've tried the following but it seems to ignore if there is nothing in the file.

awk 'NR==FNR{a[$0]++;next} !($0 in a) {print $0}' backup.doc.$(date +%y%m%d)  backup.doc.$(TZ=CST+24 date +%y%m%d) > /tmp/failed
[ -s /tmp/failed ]  && cat /tmp/failed | mailx -s "Backup Failed" user@email.com

Do it with "diff". See "man diff" for details.

Check the output of "diff" - if the files are identical the output will be empty and the return code of "diff" will also reflect that. You can use this (as well as any eventual output) to construct your mail the same way you already did in your scripts version.

I hope this helps.

bakunin

1 Like

thank you!

Sorry, one more question, can I make it not email if file2 is 0 even though there are still differences?

Of course you can:

if [ $(ls -s file2 | cut -f1) -gt 0 ] ; then
     diff file1 file2 > tmpfile
     if ....
          mail -s .....
     fi
fi

"ls -s" is the file size in blocks, if the file is empty it is 0.

I hope this helps.

bakunin

Thank you so very much!!