Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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


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

share|improve this question
up vote 4 down vote accepted

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

share|improve this answer
Perfect. That's EXACTLY what I needed to know. Thanks! – Mike B Oct 14 '12 at 18:00

You can use -s to check if a file is empty:

if [[ -s $FILE ]] ; then
echo "$FILE has data."
echo "$FILE is empty."

If you want to know whether a string is empty or not, use the option -z to check if empty:

if [[ -n "$STRING" ]]; then
    echo "String is not empty"

or -n to check if not empty:

if [[ -z "$STRING" ]]; then
    echo "String is empty"
share|improve this answer
Thanks. How would I combine to two searches? So essentially write an if/then statement to say "If file is not empty AND if blah blah"... – Mike B Oct 14 '12 at 7:21
As documented in test(1) use -a to connect to expressions with an AND operation. – Ansgar Wiechers Oct 14 '12 at 12:25

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.