$_ CLI In Depth
Learning progress 0%
build files globbing find

Build: A Duplicate File Finder

5 min read Module 4: File Manipulation, Globbing & find Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:13

The specification

Write a script named /workspace/dupes.sh. It takes one argument, a directory. It walks every regular file under that directory in sorted path order. For each file, it computes a checksum of the contents. The first file with a given checksum is the original and is not printed. Every later file with the same checksum is printed, one path per line, using the path as find reports it under the argument. If the number of arguments is wrong, it prints a usage line to standard error and exits with status 2.

For the sample directory that the lab creates, the expected output is two lines: the duplicate of a.txt in the top level, and the duplicate in a subdirectory. The checker compares the output exactly, so the paths and their order must match.

Why a checksum and not a name

Two files with the same name in different directories are not duplicates, and two files with different names can hold identical bytes. The only reliable way to decide that two files are the same is to compare their contents. Comparing every pair directly is slow for a large directory. A checksum reduces each file to a short fixed value, so you only compare values, and then you can confirm a match with cmp when the stakes are high. For this build, a checksum is accurate enough, because a collision between two different files is extremely unlikely with a strong digest.

Collect the files safely

Use find with -type f and -print0, and sort the NUL-separated list with sort -z, which GNU sort supports. Reading the list with read -d and an empty delimiter keeps names with spaces and newlines intact. The loop must never split a path on whitespace, which is the reason the NUL delimiter is essential.

Track the first file of each checksum

An associative array keyed by the checksum is the natural structure. Bash supports associative arrays with declare -A. When a checksum is new, store the path as the original. When it already exists, print the current path. The array must be declared before the loop, and it must be declared once, because re-declaring it would clear the map.

Checking your work

Create the sample tree in the first lab step. Run the script on the directory. If it prints the original as well as the duplicate, check the order of the first checksum test. If it prints nothing, check that find finds files and that the checksum field is correct. The checksum tool prints the digest and the name, so take only the first field.

Design choices in the reference

The reference reads the whole list before it prints anything, because sort -z is a separate stage in the pipeline. For a directory with millions of files, that means the sort holds the full list in memory or on disk, and the first duplicate appears late. A streaming design would print matches as they are found, but then it could not report the first file of a group in sorted order. The trade-off is visible in the code, and a good build report explains which side of it you chose.

The reference computes a checksum for every file, including files whose sizes are unique. A common optimization groups files by size first and checksums only the groups with two or more members. You can add that step as an extension, and the output must stay the same, which makes it a good test of understanding.

Reference solution

The reference solution is short. It validates its argument, walks the sorted list of files, and uses an associative array to recognize repeated checksums. Read it after your own attempt, and compare the choices for the NUL handling and for the checksum field.

BASH14 lines
#!/usr/bin/env bash
# dupes.sh DIR: print each file whose content matches an earlier file
set -eu
[ $# -eq 1 ] || { echo "usage: dupes.sh DIR" >&2; exit 2; }
declare -A first=()
while IFS= read -r -d '' f; do
  sum=$(md5sum "$f")
  sum=${sum%% *}
  if [ -n "${first[$sum]:-}" ]; then
    printf '%s\n' "$f"
  else
    first[$sum]=$f
  fi
done < <(find "$1" -type f -print0 | sort -z)

The loop reads each path with the NUL delimiter and computes its digest. The parameter expansion removes everything after the first space, which leaves the digest. The process substitution feeds the sorted list to the loop without a subshell, so the array keeps its contents.

Common mistakes to watch for

The first mistake is reading the checksum output without stripping the name, which makes every file look unique. The second is putting the pipeline on the left of the loop, which runs the loop in a subshell and loses the array. The third is printing the original as well as the duplicates. The fourth is using a name-based test instead of a content test. Run the script on a tree where two files share a name but differ in content, and confirm that it prints nothing for that pair.

Extensions to try

Add an option that prints the group of identical files together, or add a check with cmp to confirm each match before printing. Each extension teaches a different skill. Keep the script readable, and use the checker output as the guide for every change.

Terminal lab · 2 steps · real Linux in your browser

Build dupes.sh step by step

Create a tree with two duplicates, then write a script that prints the later copies.

01
Create the sample tree
Create files/a.txt with the text same, then make two copies of it: files/b.txt and files/sub/d.txt. Also create files/c.txt with different text: ``bash cd /workspace mkdir -p files/sub printf 'same\n' > files/a.txt cp files/a.txt files/b.txt cp files/a.txt files/sub/d.txt printf 'other\n' > files/c.txt ``
Show hint for step 1
cp makes an identical copy, so b.txt and d.txt match a.txt.
02
Write dupes.sh
Write /workspace/dupes.sh. It takes one directory, walks its regular files in sorted order with a NUL-separated list, computes a checksum for each, and prints every file whose checksum already appeared. Use an associative array declared with declare -A. Run it with: bash dupes.sh files. The output must be exactly the two lines files/b.txt and files/sub/d.txt.
Show hint for step 2
Use [[ -v first[$sum] ]] to test whether a key exists. Feed the loop with process substitution so the array keeps its values.
Check yourself Question 1 of 4
Concept Check Storing first paths recall

Which bash feature does the reference use to remember the first path for each checksum?

Recap & Key Takeaways

Compare file contents with a checksum rather than names, and confirm important matches with cmp.
Use find -print0, sort -z, and read -d with a NUL delimiter so that every file name survives the pipeline.
Keep the associative array outside any subshell, which is why the reference uses process substitution.
Strip the file name from the checksum output before using it as a key.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue