$_ CLI In Depth
Learning progress 0%
Build · File Manipulation, Globbing & find

Build: A Duplicate File Finder

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

~30 min Beginner 2 checked steps

Build it on a real Linux machine

The guided lab boots Linux in your browser. Each step runs a check script on that machine, so it passes only when your files and output are right.

What you will build

Step 1: 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:

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

Step 2: 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.

Files

  • dupes.sh: the finished script.
  • walkthrough.sh: every step of the reference solution, in order.

How it is checked

Each step in the guided lab has a check script that runs on the lab machine after you finish. It passes only when the files and output it expects are there, so the lab cannot be completed by reading alone.

Reference files

Read these after you have tried the lab. They are the solutions the checks were verified against.

dupes.sh

BASH12 lines
#!/usr/bin/env bash
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" | cut -d' ' -f1)
  if [[ -v first[$sum] ]]; then
    printf '%s\n' "$f"
  else
    first[$sum]=$f
  fi
done < <(find "$1" -type f -print0 | sort -z)

walkthrough.sh

BASH28 lines
#!/usr/bin/env bash
# Reference solution for every step of the guided lab, in order.

# Step 1: Create the sample tree
cd /workspace
mkdir -p files/sub
printf &#039;same\n&#039; > files/a.txt
cp files/a.txt files/b.txt
cp files/a.txt files/sub/d.txt
printf &#039;other\n&#039; > files/c.txt

# Step 2: Write dupes.sh
cd /workspace
cat > dupes.sh <<&#039;EOF&#039;
#!/usr/bin/env bash
set -eu
[ $# -eq 1 ] || { echo "usage: dupes.sh DIR" >&2; exit 2; }
declare -A first=()
while IFS= read -r -d &#039;&#039; f; do
  sum=$(md5sum "$f" | cut -d&#039; &#039; -f1)
  if [[ -v first[$sum] ]]; then
    printf &#039;%s\n&#039; "$f"
  else
    first[$sum]=$f
  fi
done < <(find "$1" -type f -print0 | sort -z)
EOF
bash dupes.sh files > /dev/null

Lessons this build uses