Skip to content

Instantly share code, notes, and snippets.

@AdamGagorik
Created October 10, 2025 16:19
Show Gist options
  • Save AdamGagorik/bf6d77cac3ea27405528a88553610fdf to your computer and use it in GitHub Desktop.
Save AdamGagorik/bf6d77cac3ea27405528a88553610fdf to your computer and use it in GitHub Desktop.
Count files
#!/usr/bin/env bash
set -euo pipefail
show_usage() {
echo "Usage: $0 [--max-depth N] <ext> <ext> ..."
}
# parse options
opts=$(getopt -o h --long help,max-depth: -- "$@")
if [ $? != 0 ]; then
echo "Failed to parse options." >&2
exit 1
fi
eval set -- "$opts"
MAX_DEPTH=""
while true; do
case "$1" in
--max-depth)
MAX_DEPTH="$2"
shift 2
;;
-h|--help)
show_usage
exit 0
;;
--)
shift
break
;;
*)
break
;;
esac
done
# ensure extensions are provided
if [ "$#" -eq 0 ]; then
show_usage
exit 0
fi
# figure out the max extension length
max_len=1
for arg in "$@"; do
if [ "${#arg}" -gt "$max_len" ]; then
max_len="${#arg}"
fi
done
count_files() {
local ext="$1"
if [ -n "${MAX_DEPTH}" ]; then
fd --extension "${ext}" --max-depth "${MAX_DEPTH}" -u -L | wc -l
else
fd --extension "${ext}" -u -L | wc -l
fi
}
# count files for each extension
for ext in "$@"; do
count="$(count_files "${ext}")"
printf "%-${max_len}s: %d\n" "${ext}" "${count}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment