Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


All files equals


Files are not all equals
share|improve this question
up vote 14 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 $?
$ echo >>file3
$ diff -q --from-file file1 file2 file3 file4; echo $?
Files file1 and file3 differ
share|improve this answer

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
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

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.

# diffseveral

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


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


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

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
    echo Not

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

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

if alleq file1 file2 ...; then
    echo All equal
    echo Not
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

Your Answer


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.