Created
September 10, 2022 20:58
-
-
Save koonix/d90ac0b115254b6d78f208d92858f594 to your computer and use it in GitHub Desktop.
a wrapper for rm to stop it from recursively removing top-level directories.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/zsh | |
# a wrapper for rm to make it safer to use. | |
# it stops rm from recursively removing top-level directories. | |
unset recursive endopt | |
# check arguments | |
for arg; do case $arg in | |
--) break ;; | |
--one-file-system|--interactive*|--dir) ;; | |
--*preserve-*|--verbose|--version) ;; | |
-*f*|--force) echo '-f or --force is not allowed.'; exit 1 ;; | |
-*[rR]*|--recursive) recursive=1 ;; | |
esac; done | |
# function to check wether the given directory is high-level | |
issafe() | |
{ | |
local paths=("${1:?}" "${1:P}") | |
for p in "$paths[@]"; do | |
[[ $p =~ ^(/[^/]+){1,3}/?$ ]] && return 1 | |
[[ $p =~ ^/home(/[^/]+){1,4}/?$ ]] && return 1 | |
[[ $p =~ ^/media(/[^/]+){1,3}/?$ ]] && return 1 | |
[[ $p =~ ^/mnt(/[^/]+){1,4}/?$ ]] && return 1 | |
done | |
return 0 | |
} | |
# check paths | |
(( recursive )) && for arg; do | |
! (( endopt )) && [[ $arg == -- ]] && endopt=1 && continue | |
! (( endopt )) && [[ $arg == -* ]] && continue | |
issafe "$arg" && continue | |
echo 'recursively removing sensitive directories is not allowed.' | |
exit 1 | |
done | |
exec rm -iv --one-file-system "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment