#!/usr/bin/env bash # rename_postfix.sh [-n|--dry-run] [-v] POSTFIX REPLACEMENT set -o errexit -o pipefail set -o nounset dry_run=0 verbose=0 # ---- Parse flags while [[ $# -gt 0 ]]; do case "$1" in -n|--dry-run) dry_run=1; shift ;; -v|--verbose) verbose=1; shift ;; --) shift; break ;; -*) echo "Unknown option: $1" >&2; exit 2 ;; *) break ;; esac done if [[ $# -lt 2 ]]; then echo "Usage: ${0##*/} [-n|--dry-run] [-v] old_extension new_extension" >&2 echo "Example: $0 .env .sh" exit 2 fi old_ext="$1" new_ext="$2" if [[ -z "$new_ext" ]]; then echo "Refusing to run: new_ext cannot be empty." >&2 exit 2 fi # Match files in current dir whose names start with $postfix # nullglob: if no matches, the glob expands to nothing (prevents literal) shopt -s nullglob # Include dotfiles if the postfix starts with a dot (like .env) # (Bash already matches dotfiles when the pattern itself starts with a dot.) # Handle spaces safely by quoting $f everywhere. for file in *"$old_ext"; do [[ -e "$file" ]] || continue base="${file%$old_ext}" # strip the old extension new_file="${base}${new_ext}" # Skip if nothing changes [[ "$file" == "$new_file" ]] && continue if (( dry_run )); then printf '[DRY-RUN] mv -- %q %q\n' "$file" "$new_file" else # -n: don't overwrite existing files accidentally # Add -v if requested if (( verbose )); then mv -vn -- "$file" "$new_file" else mv -n -- "$file" "$new_file" fi fi done