Bash: using the result of a diff in a if statement

Viewed 91140

I am writing a simple Bash script to detect when a folder has been modified.

It is something very close to:

ls -lR $dir > a
ls -lR $dir > b

DIFF=$(diff a b) 
if [ $DIFF -ne 0 ] 
then
    echo "The directory was modified"

Unfortunately, the if statement prints an error: [: -ne: unary operator expected

I am not sure what is wrong with my script, would anyone please be able to help me?

Thank you very much!

Jary

5 Answers

If you don't need to know what the changes are, cmp is enough. Plus you can play with the syntactical trick provided by && and || :

cmp a b || echo 'The directory was modified'

The instruction may be interpreted as: "either a and b are equal, or i echo the message".

(The semantic of && and || must be handled with care, but here it's intuitive).

Just for the sake of readability, i actually prefer to put it on two lines:

cmp a b \
  || echo 'The directory was modified'
Related