Skip to content

Instantly share code, notes, and snippets.

@Saruspete
Last active December 14, 2020 11:54
Show Gist options
  • Save Saruspete/a3a559c842e219b258f1bab249c99846 to your computer and use it in GitHub Desktop.
Save Saruspete/a3a559c842e219b258f1bab249c99846 to your computer and use it in GitHub Desktop.
A wrapper over rm to protect critical paths from accidental deletion
# Override RM to protect critical folders. Regex
typeset -gxa MYS_RM_PROTECT=(
"$HOME/[^/]+"
"/root/.+"
)
# TODO: 2 unhandled cases:
# - protected path contains a symlink
# - recursive parent deletion
function rm {
typeset todel= safedir= confirmdir=""
# Scan for protected paths
for todel in "$@"; do
typeset todelabs="$(readlink -f "$todel" 2>/dev/null || realpath "$todel")"
for safedir in "${MYS_RM_PROTECT[@]}"; do
# Check with relative or absolute path
if [[ "$todel" =~ ^$safedir ]] || [[ "$todelabs" =~ ^$safedir$ ]]; then
confirmdir+=" - '$todel' folder '$todelabs' safedir '$safedir'\n"
fi
done
done
# Check if we have protected paths
if [[ -n "$confirmdir" ]]; then
echo >&2 "!!!!!!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo >&2 "You are about to remove content in a protected dir. Matched entries:"
echo >&2 -e "$confirmdir"
typeset answer=""
while [[ "$answer" != "YES" ]]; do
echo >&2 "!! Are you sure ? Enter 'yes' in UPPERCASE to confinue, Ctrl+C to cancel !!"
read answer
done
fi
# Call real rm binary
$(type -P rm) "$@"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment