karawaci.kode

← Semua snippet

Bash Menengah Utility

Find duplicate files berdasarkan content hash

Cari file yang isinya identical (bukan cuma nama yang sama) di sebuah directory. Pakai SHA-256 hash. Hasil: list duplikat dengan path.

Dipublikasikan 3 Juni 2026

Folder Pictures saya penuh foto duplikat karena import berkali-kali dari HP, restore backup, copy dari teman. Filename beda, isinya sama. Snippet ini cari file duplikat berdasarkan SHA-256 hash dari content.

Kode

#!/usr/bin/env bash
# find-dupes.sh — cari file duplikat berdasarkan SHA-256
# Usage: ./find-dupes.sh /path/to/directory

DIR="${1:-.}"

find "$DIR" -type f -size +1k -print0 \
  | xargs -0 sha256sum \
  | sort \
  | awk '
      { hash=$1; $1=""; sub(/^ /, ""); path=$0;
        if (hash == prev_hash) {
          if (!group_printed) { print "=== Duplicate ==="; print "  " prev_path; group_printed=1 }
          print "  " path
        } else { group_printed=0 }
        prev_hash=hash; prev_path=path
      }
    '

Output sample

=== Duplicate ===
  /Users/me/Pictures/2024/IMG_001.jpg
  /Users/me/Downloads/IMG_001.jpg
  /Users/me/Pictures/import-backup/photo_001.jpg
=== Duplicate ===
  /Users/me/Documents/proposal.pdf
  /Users/me/Desktop/proposal copy.pdf

Kapan dipakai

  • Bersihkan folder Pictures yang punya banyak import duplicate
  • Audit Downloads folder
  • Sebelum delete files: tahu mana yang ada copy lain

Catatan

  • -size +1k skip file kecil (icon, dotfiles) untuk speed
  • SHA-256 untuk akurasi 100%: 2 file dengan hash sama = byte-by-byte identical
  • Untuk dataset besar (1TB+), pakai MD5 lebih cepat 2x tapi ada risiko collision teoretis (untuk dedup personal: acceptable)
  • Script tidak menghapus apapun — review output dulu, baru rm manual

Variasi: include filesize sebelum hash (lebih cepat)

# Pre-filter berdasarkan ukuran, baru hash kalau ukuran sama
find "$DIR" -type f -size +1k -printf '%s %p\n' \
  | sort -n \
  | awk '
      { size=$1; $1=""; path=substr($0,2);
        sizes[size] = sizes[size] "\n" path; count[size]++
      }
      END {
        for (s in count) if (count[s] > 1) print sizes[s]
      }
    ' \
  | xargs -d'\n' -I{} sha256sum {} | sort | ...

Trick: hash hanya kalau ukuran sama. Untuk 100k+ file: 5x lebih cepat.

Untuk dedup berskala, pakai fdupes atau rmlint — tool dedicated. Snippet ini untuk understanding dan small ad-hoc cleanup.

# tags

deduphashfindcleanup

Ditulis oleh Asti Larasati · 3 Juni 2026