#!/bin/bash # screenshot-rename - watch for new macOS screenshots and rename them to a timestamp-only format # # Usage: # screenshot-rename [-p|--path PATH] [-F|--format FORMAT] [--utc] # screenshot-rename -h # # Options: # -p, --path PATH Directory to watch (default: macOS configured screenshot # location from `defaults read com.apple.screencapture location`, # falling back to ~/Desktop) # -F, --format FORMAT strftime format for the new filename (default: "%Y-%m-%d %H.%M.%S") # -u, --utc Use UTC timezone instead of local time # -h, --help Show help message _screenshot_rename() ( local SCRIPT_NAME; SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")" case "${BASH_SOURCE[0]}" in /dev/*|/proc/*) SCRIPT_NAME="" ;; esac case "$SCRIPT_NAME" in ""|bash|sh|zsh|dash) SCRIPT_NAME="screenshot-rename" ;; esac _error() { echo "[ERR][$SCRIPT_NAME] $*" >&2; } _show_help() { local s; [ -t 1 ] && s=$'\033[4m' local r; [ -t 1 ] && r=$'\033[24m' cat </dev/null 2>&1; then _error "fswatch is required" return 3 fi # Determine watch directory: --path wins. Otherwise, try the macOS-configured # screenshot location; fall back to ~/Desktop if that fails or isn't a dir if [ -z "$watch_dir" ]; then watch_dir="$(defaults read com.apple.screencapture location 2>/dev/null)" # Expand ~/ if present (defaults may return "~/Desktop" literally) watch_dir="${watch_dir/#\~/$HOME}" if [ -z "$watch_dir" ] || [ ! -d "$watch_dir" ]; then watch_dir="$HOME/Desktop" fi fi echo "Watching for new screenshots in: $watch_dir" local path fswatch -0 "$watch_dir" | while IFS= read -r -d '' path; do case "$path" in "$watch_dir"/Screenshot\ *.png) # We get multiple lines for a single screenshot, so the file may already be moved [ -f "$path" ] || continue printf %s "Renaming screenshot: $path" # Choose time zone local timestamp if [ "$use_utc" = true ]; then timestamp="$(TZ=Etc/UTC date "+$fmt")" else timestamp="$(TZ=/etc/localtime date "+$fmt")" fi local dest="$watch_dir/$timestamp.png" # In case two renames are attempted at the same time, ensure unique names local i=1 while [ -e "$dest" ]; do dest="$watch_dir/$timestamp-$i.png" i=$((i + 1)) done echo " -> $(basename "$dest")" mv "$path" "$dest" ;; esac done ) _screenshot_rename "$@" __screenshot_rename_rc=$? unset -f _screenshot_rename if [ -n "${BASH_SOURCE[0]}" ] && [ "${BASH_SOURCE[0]}" != "$0" ]; then eval "unset __screenshot_rename_rc; return $__screenshot_rename_rc" fi eval "unset __screenshot_rename_rc; exit $__screenshot_rename_rc"