Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

diff

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

like image 457
Jary Avatar asked Aug 31 '10 18:08

Jary


3 Answers

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

DIFF=$(diff a b) 
if [ "$DIFF" != "" ] 
then
    echo "The directory was modified"
fi
like image 101
Lou Franco Avatar answered Nov 15 '22 03:11

Lou Franco


if ! diff -q a b &>/dev/null; then
  >&2 echo "different"
fi
like image 60
Paul Tomblin Avatar answered Nov 15 '22 01:11

Paul Tomblin


You are looking for the return value of diff and not the output of diff that you are using in your example code.

Try this:

diff a b
if [ $? -ne 0 ]; then
    echo "The directory was modified";
fi
like image 32
tangens Avatar answered Nov 15 '22 02:11

tangens