Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a number of files, I want to check that all those files have the same content.

What command line could I use to check that?

Usage could be something like:

$ diffseveral file1 file2 file3 file4

Result:

All files equals

OR

Files are not all equals
share|improve this question
add comment

4 Answers

up vote 6 down vote accepted

With GNU diff, pass one of the files as an argument to --from-file and any number of others as operand:

$ diff -q --from-file file1 file2 file3 file4; echo $?
0
$ echo >>file3
$ diff -q --from-file file1 file2 file3 file4; echo $?
Files file1 and file3 differ
1
share|improve this answer
add comment

The following code should be fairly self explanatory. $# is the number of file arguments, and shift just consumes them one at a time. Uses cmp -s for silent byte-wise comparison.

#!/bin/sh
# diffseveral

if [ $# -lt 2 ]; then
    printf '%s\n' "Usage: $0 file1 file2 [files ...]" >&2
    exit 2
fi

oldfile="$1"
shift

while [ $# -gt 0 ]; do
    newfile="$1"
    if ! cmp -s "$oldfile" "$newfile"; then
         echo 'Files differ.'
         exit 1;
    fi

    shift
done

echo 'All files identical.'
exit 0
share|improve this answer
add comment

How about:

md5sum * | awk 'BEGIN{rc=1}NR>1&&$1!=last{rc=0}{last=$1}END{exit rc}'

Calculates the MD5 value for each file, then compares each entry with the next, if any are different, then return a zero (true) exit status. This would be much shorter if it returned false if different:

md5sum * | awk 'NR>1&&$1!=last{exit 1}{last=$1}'

There is no need to sort since we are just checking if any are different.

share|improve this answer
1  
In the shorter version, I guess $1 should be used, as $0 contains file name which is unique. –  xanpeng Mar 7 '12 at 6:33
add comment

You can only diff two at a time, but it's fairly easy to check if they're all equal:

if diff file1 file2 && diff file2 file3 && diff file3 file4; then
    echo All equal
else
    echo Not
fi

If you have enough to justify a loop, use something like this:

alleq () {  
    for file; do 
        diff -q "$1" "$file" >/dev/null || return 1
    done
}

if alleq file1 file2 ...; then
    echo All equal
else 
    echo Not
fi
share|improve this answer
    
Clumsy if you have fifty files, or don't know how many –  DarenW Oct 21 '13 at 21:57
    
@DarenW Sure, if you have that many just use a loop. –  Kevin Oct 21 '13 at 22:09
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.