Diff in Bash Script?

I've been toying around with makefiles and bash scripts and I'm interested in this:

Is it possible to get a boolean value from a diff(or something similar) so that I can use it in a bash script to evaluate an if statement(so that the user will not see the actual diff executing)?

3 Answers

If all you need is a byte-by-byte comparison, use cmp:

if cmp -s "$a" "$b"; then
    echo Same
else
    echo Differ
fi

This avoids wasting time for diff's difference finding algorithm.

1

Yes:

if diff "$file_a" "$file_b" &> /dev/null ; then
    echo "Files are the same"
else
    echo "Files differ"
fi

The manual is not clear on the return codes. However, diff should return always 0 when you compare two identical files.

diff -a $file1 $file2 > /dev/null 2>&1

if [ $? -eq 0 ]
then
    ...
fi
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest