Skip to content

Instantly share code, notes, and snippets.

@AdamGagorik
Created October 1, 2025 18:31
Show Gist options
  • Save AdamGagorik/6efaf87a800d5200cfee7fa4ff14a091 to your computer and use it in GitHub Desktop.
Save AdamGagorik/6efaf87a800d5200cfee7fa4ff14a091 to your computer and use it in GitHub Desktop.
Rsync based directory removal
#!/usr/bin/env bash
set -e
if [ -z "${1}" ]; then
echo "Usage: $(basename "${0}") <path>"
exit 1
fi
TO_REMOVE=$(realpath "${1}")
if [ "${2}" = "--force" ]; then
NO_PROMPT=true
else
NO_PROMPT=false
fi
echo "Attempting to remove ${TO_REMOVE}."
if [ -d "${TO_REMOVE}" ]; then
if [ "${NO_PROMPT}" != true ]; then
read -r -p "Are you sure you want to remove this directory? (y/n): " CONFIRM
fi
if [[ "${CONFIRM}" =~ ^[Yy]$ ]] || [ "${NO_PROMPT}" = true ]; then
TEMP_PATH=$(mktemp -d)
rsync -av --prune-empty-dirs --info=progress2 --delete "${TEMP_PATH}/" "${TO_REMOVE}/"
rmdir "${TO_REMOVE}"
echo "Removed ${TO_REMOVE}."
exit 0
else
echo "Removal cancelled."
exit 1
fi
else
echo "The specified path is not a directory."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment