views:

198

answers:

4

I want to compare two files and see if they are the same or not in my shell script, my way is:

diff_output=`diff ${dest_file} ${source_file}`

if [ some_other_condition -o ${diff_output} -o some_other_condition2 ]
then
....
fi

Basically, if they are the same ${diff_output} should contain nothing and the above test would evaluate to true.

But when I run my script, it says
[: too many arguments

On the if [....] line.

Any ideas?

+1  A: 

There's an option provided precisely for doing this: -q (or --quiet). It tells diff to just let the exit code indicate whether the files were identical. That way you can do this:

if diff -q "$dest_file" "$source_file"; then
    # files are identical
else
    # files differ
fi

or if you want to swap the two clauses:

if ! diff -q "$dest_file" "$source_file"; then
    # files differ
else
    # files are identical
fi

If you really wanted to do it your way (i.e. you need the output) you should do this:

if [ -n "$diff_output" -o ... ]; then
    ...
fi

-n means "test if the following string is non-empty. You also have to surround it with quotes, so that if it's empty, the test still has a string there - you're getting your error because your test evaluates to some_other_condition -o -o some_other_condition2, which as you can see isn't going to work.

Jefromi
+2  A: 

Do you care about what the actual differences are, or just whether the files are different? If it's the latter you don't need to parse the output; you can check the exit code instead.

if diff -q "$source_file" "$dest_file" > /dev/null; then
    : # files are the same
else
    : # files are different
fi

Or use cmp which is more efficient:

if cmp -s "$source_file" "$dest_file"; then
    : # files are the same
else
    : # files are different
fi
John Kugelman
+1  A: 

diff is for comparing files line by line for processing the differences tool like patch . If you just want to check if they are different, you should use cmp:

cmp --quiet $source_file $dest_file || echo Different
Jürgen Hötzel
A: 

diff $FILE $FILE2 if [ $? = 0 ]; then echo “TWO FILES ARE SAME” else echo “TWO FILES ARE SOMEWHAT DIFFERENT” fi

arun