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?

5 Answers 5

16

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

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

Comments

0

Check files for difference in bash

source_file=abc.txt
dest_file=xyz.txt

if [[ -z $(sdiff -s $dest_file $source_file) ]]; then  

   echo "Files are same"

else

   echo "Files are different"

fi

Code tested on RHEL/CentOS Linux (6.X and 7.X)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.