Find Duplicate Files in Perl and Python: Three Bugs in My 2014 Tutorial

In 2014 I published a tutorial with a Perl script to find duplicate files. The script is 37 lines long, with comments. I built a test tree to break it, and I read the tutorial text again. I found three bugs: two in the script and one in the text next to it. This post shows each bug, the fix, and the same fixed program in Python. I posted a short version of this on LinkedIn.

I did this work with an AI assistant. It helped me review the script and write the fixes in Perl and Python. I ran the tests on my own machine. The assistant ran them in a second environment. I checked each result against a separate SHA-256 grouping.

All of the code in this post is under GPL 3.0, the same license as the 2014 original.

How to find duplicate files with find and cksum

The script has two steps. First, find lists every file that has one suffix. Second, cksum reads each file and prints a checksum. The script groups the file names by checksum. A checksum with two or more names is a set of duplicates.

The idea is good. Unix tools do the hard work, and Perl joins them with a hash of arrays.

The original script

#!/usr/bin/perl

# Author: Jeff Wilson
# Created: 2014
# License: GPL 3.0 ... no warranty, free to re-use in any way

use warnings;
use strict;

# read a command line argument, complain if it isn't set
my $type = shift || die "Expecting filetype suffix";

my %files;
# search through the file system, beginning in the directory where invoked
open(my $ph,"find . -type f -iname \"*.$type\"|");
while (<$ph>) {
  # grab the line of output from the < > operator, rename to $file
  my $file = $_;
  # eat the newline off the end of the line
  chomp $file;
  my $cksumOut;
  # pass this file into the cksum utility, chomp the output
  chomp ($cksumOut = `cksum "$file"`);
  # split the columns by whitespace
  my ($cksum,$size,$name) = split /\s+/,$cksumOut,3;
  # store filenames by their checksum to look for collisions
  push @{$files{$cksum}}, $file;
}
close $ph;

# walk through all the computed checksums
for my $csum (keys %files) {
  # skip any arrays with less than 2 entries
  next unless (scalar @{$files{$csum}} > 1);
  # report anything with 2 or more entries
  print join("\n",$csum,map { "\t$_" } @{$files{$csum}}),"\n";
}

The test tree

I built the tree with a short Python program. All of the files are invented. The tree has 22 files:

  • Three true copies of one file, and two true copies of a second file.
  • Two files of equal size with different content.
  • One file with content of its own.
  • Two files of 24 bytes each with different content but the same cksum value.
  • Six files with unusual names: a space, a quote, a dollar sign, a command substitution, a backtick, and a newline.
  • Two true copies with unusual names, in a folder of their own.
  • Four files that each have a size that no other file has.

A file name with a newline counts twice in find . -type f | wc -l, so that command shows 23 lines for these 22 files.

The correct answer is three sets of duplicates: the first group of three, the group of two, and the two copies with unusual names. Run the original script on this tree and it prints four sets. Only two of them are correct.


    ./hostile-dup/$(touch PWNED2).txt
    ./hostile-dup/a "quote" copy.txt
    ./hostile/new
    line.txt
    ./hostile/back`tick.txt
    ./hostile/dollar$HOME.txt
    ./hostile/a "quote".txt
    ./hostile/$(touch PWNED).txt
2050441504
    ./collide/x.txt
    ./collide/y.txt
75150150
    ./backup/b2.txt
    ./docs/b1.txt
1779984116
    ./backup/a3.txt
    ./docs/a1.txt
    ./docs/sub/a2.txt

The set with a blank first line has an empty key. Bug 2 explains it. The order of the sets can change from one run to the next, because a Perl hash has no fixed order. The program exited with status 0 and printed a report. Nothing told the reader that the report was wrong.

Bug 1: cksum is a CRC

The cksum program prints a 32-bit CRC. A CRC finds accidental changes in a file. It does not make sure that two different files have two different values. In the test tree, two files of 24 bytes have different content and the same cksum value:

$ cksum collide/x.txt collide/y.txt
2050441504 24 collide/x.txt
2050441504 24 collide/y.txt
$ cmp collide/x.txt collide/y.txt
collide/x.txt collide/y.txt differ: byte 1, line 1
$ sha256sum collide/x.txt collide/y.txt
6e9ab6ff9265bb3c8269cd141c12ea048bc82048dad464b9ada3d0da99bb5230  collide/x.txt
0790a122502258245f9c890ed1c6cb9d66ae61b96c0aff04710307e41a7198be  collide/y.txt

The original script printed these two files as one set of duplicates (the set under 2050441504 above). A SHA-256 digest separates them.

To make the pair yourself, write these 24-byte values to two files and run cksum on both:

$ echo 6cf14e8f6798dc7a99e206061eb3025c52167b419f220a2c | xxd -r -p > x.bin
$ echo 5abbd0c0cd1ea956341509c454ca4ba1a25cdf0f9d7de36e | xxd -r -p > y.bin
$ cksum x.bin y.bin
2050441504 24 x.bin
2050441504 24 y.bin
$ cmp x.bin y.bin
x.bin y.bin differ: byte 1, line 1

The error is small in a tree of a few files. It grows with the number of files. A 32-bit value gives an even chance of at least one false match in a set of about 77,000 files. A backup disk can hold that many.

Bug 2: the shell reads the file name

The script builds a shell command from the file name:

chomp ($cksumOut = `cksum "$file"`);

Perl puts the name in the string. Then the shell reads the string again. In the shell, some characters have a meaning. A name that contains $(touch PWNED) runs the touch command. In the test tree, one file has that name. After the run, the marker files exist:

$ ls PWNED PWNED2
PWNED
PWNED2

I used touch because it is harmless. A hostile name could hold any command.

The other unusual names fail in other ways. A backtick in a name stops the shell with a syntax error. A quote in a name changes where the quoted text ends. A newline in a name splits one path into two lines of find output. The first lines of the error output show the effect:

cksum: ./hostile-dup/.txt: No such file or directory
Use of uninitialized value $cksum in hash element at find-duplicate.pl line 27, <$ph> line 9.
cksum: './hostile-dup/a quote copy.txt': No such file or directory
Use of uninitialized value $cksum in hash element at find-duplicate.pl line 27, <$ph> line 10.

When cksum fails, the variable $cksum has no value. All of those files then go under one blank key. In the output above, that blank key holds seven files. Two of them are true copies. Five of them are not related. The report hides the one real result in that group.

Bug 3: a loop that stops early

This bug is not in the script. It is in the tutorial text. The section on lists says that $#arr holds the value of the highest defined index. The example loop under that sentence is:

for (my $i=0; $i < $#arr; $i++) { print $arr[$i]; }

In Perl, $#arr is the last index, not the count. The text is right, and the example is wrong. The test $i < $#arr stops one item early. On an array of three items, the loop prints two:

a b 
array has 3 elements

The fix is <=, or a foreach loop that has no index. With <= the loop prints all three items:

a b c 

The Perl rewrite

Three changes fix Bug 1 and Bug 2 and remove one cost problem. Bug 3 has its own fix above:

  1. Digest::SHA (SHA-256) replaces cksum.
  2. File::Find and an in-process read replace the find pipe and the backticks. A file name is never given to a shell.
  3. The program groups the files by size first. It opens and hashes only the files that share a size with another file.
#!/usr/bin/perl
# find-duplicate-v2.pl -- 2026 rewrite of the 2014 find-duplicate.pl
# Usage: find-duplicate-v2.pl SUFFIX [DIR]
#
# Original author: Jeff Wilson (2014), GPL 3.0. This rewrite keeps that license.
#
# Three fixes over the 2014 version:
#   1. SHA-256 (Digest::SHA) replaces cksum, which is a CRC and can collide.
#   2. File::Find and in-process reads replace the find|backtick pipeline,
#      so a filename is never given to a shell.
#   3. Files are grouped by size first; only files that share a size are hashed.

use strict;
use warnings;
use File::Find;
use Digest::SHA;

my $type = shift // die "Usage: $0 SUFFIX [DIR]\n";
my $dir  = shift // '.';

# case-insensitive match on the end of the name, like find -iname "*.$type"
my $suffix_re = qr/\.\Q$type\E\z/i;

# Pass 1: walk the tree, group paths by size. No file is opened yet.
my %by_size;
find(
    {
        no_chdir => 1,
        wanted   => sub {
            return unless -f $_ && !-l $_;      # regular files only
            return unless $_ =~ $suffix_re;
            push @{ $by_size{ -s _ } }, $File::Find::name;
        },
    },
    $dir
);

# Pass 2: hash only the files that share a size with at least one other file.
my %by_hash;
for my $size ( keys %by_size ) {
    my @paths = @{ $by_size{$size} };
    next if @paths < 2;                          # a unique size cannot be a duplicate
    for my $path (@paths) {
        # three-argument open: the name is data, never a shell command
        open( my $fh, '<:raw', $path ) or do { warn "skip $path: $!\n"; next };
        my $digest = Digest::SHA->new(256)->addfile($fh)->hexdigest;
        close $fh;
        push @{ $by_hash{$digest} }, $path;
    }
}

# Report: groups with 2 or more files. Sorted so output is repeatable.
my @groups =
  sort { $a->[1][0] cmp $b->[1][0] }
  map  { [ $_, [ sort @{ $by_hash{$_} } ] ] }
  grep { @{ $by_hash{$_} } > 1 } keys %by_hash;

for my $g (@groups) {
    my ( $digest, $paths ) = @$g;
    print "$digest\n";
    for my $p (@$paths) {
        ( my $shown = $p ) =~ s/\n/\\n/g;        # show an embedded newline as \n
        print "\t$shown\n";
    }
}

The size filter also answers the warning in the 2014 article: every byte of each file must be read. Now the program skips a file that has a size of its own. In the test tree:

candidate .txt files: 22
files that share a size with another file (hashed by v2): 18
files skipped without being opened: 4

The same program in Python

The Python version has the same steps. It follows the Perl version line by line, so you can compare them. The comments marked PYTHONIC NOTE explain where Python habit differs from Perl habit.

#!/usr/bin/env python3
"""find_duplicates.py -- Python port of the 2026 Perl rewrite of find-duplicate.pl

Usage: find_duplicates.py SUFFIX [DIR]

Original author: Jeff Wilson (2014), GPL 3.0. This port keeps that license.

Same three fixes as the Perl v2: SHA-256, no shell, size pre-filter.
"""
import hashlib
import os
import sys
from collections import defaultdict

CHUNK = 1024 * 1024  # read 1 MiB at a time


def sha256_of(path):
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        # PYTHONIC NOTE: iter(callable, sentinel) is the idiom for "read until empty".
        # A Perl veteran would write while (read ...) { ... }. Style preference, not a bug fix.
        for block in iter(lambda: fh.read(CHUNK), b""):
            h.update(block)
    return h.hexdigest()


def main(argv):
    if len(argv) < 2:
        sys.exit("Usage: %s SUFFIX [DIR]" % argv[0])
    suffix = "." + argv[1].lower()
    top = argv[2] if len(argv) > 2 else "."

    # Pass 1: group paths by size. No file is opened yet.
    # PYTHONIC NOTE: defaultdict(list) is Perl's autovivification (push @{$h{$k}}, $v),
    # made explicit. In Perl the hash-of-arrays springs into being; in Python you say
    # what a missing key should become. Cause: Python prefers explicit over implicit.
    by_size = defaultdict(list)
    for root, _dirs, files in os.walk(top):
        for name in files:
            if not name.lower().endswith(suffix):
                continue
            path = os.path.join(root, name)
            if os.path.islink(path) or not os.path.isfile(path):
                continue
            by_size[os.path.getsize(path)].append(path)

    # Pass 2: hash only the files that share a size with another file.
    by_hash = defaultdict(list)
    for paths in by_size.values():
        if len(paths) < 2:
            continue
        for path in paths:
            try:
                by_hash[sha256_of(path)].append(path)
            except OSError as err:
                print("skip %s: %s" % (path, err), file=sys.stderr)

    # Report groups of 2 or more, sorted so output is repeatable.
    groups = sorted(
        ((digest, sorted(paths)) for digest, paths in by_hash.items() if len(paths) > 1),
        key=lambda g: g[1][0],
    )
    for digest, paths in groups:
        print(digest)
        for p in paths:
            print("\t" + p.replace("\n", "\\n"))


if __name__ == "__main__":
    main(sys.argv)

Two differences matter most for a Perl programmer. First, Python does not create a hash of arrays when you first use a key. The defaultdict(list) says what a missing key becomes. Second, a failed file read is an exception that you catch, and the Perl program checks the result of open. Both choices are style. Neither one changes the result.

Python 3.11 and later include hashlib.file_digest, which replaces the read loop. I used a loop so that the code also runs on Python 3.10.

Results

The Perl rewrite and the Python port ran on the same tree. They print the three correct sets, and the CRC pair is not in the output:

b6819f71ce2565f1a248cf1eb6261aa7f1b12a71f6f977375c1c11a9e73ce8ee
    ./backup/a3.txt
    ./docs/a1.txt
    ./docs/sub/a2.txt
924386eaca00c3773f44f6f4ec6290f4187cb5c20bcf90351597528634baf7ca
    ./backup/b2.txt
    ./docs/b1.txt
f366f1743867513f6f13537b4c9a88ed8d94ec3442dc81762c0c1a82e07c96e2
    ./hostile-dup/$(touch PWNED2).txt
    ./hostile-dup/a "quote" copy.txt

The two outputs have no difference, and neither program created a marker file:

diff perl-v2.out python.out: no difference
$ sha256sum docs/a1.txt docs/sub/a2.txt backup/a3.txt
b6819f71ce2565f1a248cf1eb6261aa7f1b12a71f6f977375c1c11a9e73ce8ee  docs/a1.txt
b6819f71ce2565f1a248cf1eb6261aa7f1b12a71f6f977375c1c11a9e73ce8ee  docs/sub/a2.txt
b6819f71ce2565f1a248cf1eb6261aa7f1b12a71f6f977375c1c11a9e73ce8ee  backup/a3.txt
$ ls PWNED PWNED2
ls: cannot access 'PWNED': No such file or directory
ls: cannot access 'PWNED2': No such file or directory

The assistant ran this test on Perl 5.34.0 and Python 3.10.12. I ran it again on Perl 5.40.1 and Python 3.14.4. The results were the same. The sha256sum program gave the same digest for the three true copies. That is an independent check of the Perl and Python result.

Why you should not trust this post without checking it

A code assistant can write a script like this in seconds. It can also write a tutorial about the script, and the tutorial will sound sure of itself. Sounding sure is not proof.

What you can trust is what you can check. The two files in bug 1 are 24 bytes each. They give the same cksum output and have different content. You can make them with xxd and test them in under one minute. The test tree has 22 files and an answer key from a separate SHA-256 program. If one of my claims is wrong, you can find it.

This is the value of a post like this one. The text is cheap. The checked result is not. Use an assistant to write code. Then test the code with hostile input, and keep the test.

One idea to keep

The program has two passes. The first pass groups the items by a cheap key (the size). The second pass spends effort only on groups that have more than one member. This shape is common in inventory work. You can group interfaces by VLAN, devices by model, or ARP entries by MAC address. Group by something cheap first. Then look hard only where a group has two or more members.

What is the oldest script you still run, and when did you last test it with hostile input?