#!/bin/bash
# sort-by-type.sh - move each file it receives into a subfolder named after its type,
# next to the file: Images, Documents, Archives, Installers, Videos, Audio, Other.
#
# Made for an Automator Folder Action (Run Shell Script, Pass input: as arguments),
# so every file added to the folder is filed at once. Also works by hand:
#   bash sort-by-type.sh ~/Downloads/*
# A file whose name already exists in the destination gets " 2", " 3"... added:
# nothing is overwritten. From declutr.app/blog.
set -u
for f in "$@"; do
  [ -f "$f" ] || continue                 # folders and missing files are left alone
  name=$(basename "$f")
  case "$name" in .* | *.download | *.crdownload | *.part) continue ;; esac   # hidden or still downloading
  ext=$(printf '%s' "${name##*.}" | tr '[:upper:]' '[:lower:]')
  [ "$ext" = "$name" ] && ext=""
  case "$ext" in
    jpg|jpeg|png|gif|heic|webp|tiff|tif|bmp|svg|raw|cr2|cr3|nef|arw|dng) type="Images" ;;
    pdf|doc|docx|pages|txt|rtf|md|odt|xls|xlsx|numbers|csv|ppt|pptx|key|epub) type="Documents" ;;
    zip|rar|7z|tar|gz|tgz|bz2|xz) type="Archives" ;;
    dmg|pkg|app) type="Installers" ;;
    mp4|mov|m4v|avi|mkv|webm) type="Videos" ;;
    mp3|m4a|wav|aiff|aif|flac|aac|ogg) type="Audio" ;;
    *) type="Other" ;;
  esac
  dest="$(dirname "$f")/$type"
  mkdir -p "$dest"
  target="$dest/$name"; n=2
  base="${name%.*}"; [ -z "$ext" ] && base="$name"
  while [ -e "$target" ]; do
    if [ -n "$ext" ]; then target="$dest/$base $n.$ext"; else target="$dest/$base $n"; fi
    n=$((n + 1))
  done
  mv "$f" "$target"
done
