Last active
June 7, 2016 08:32
-
-
Save suewonjp/bd54db6c959c47b81c0fd9583aeba340 to your computer and use it in GitHub Desktop.
[Bash tip] Safer 'rm -rf' command
This file contains 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/sh | |
scriptName=${0##*/} | |
if [ $# = 0 ] ; then | |
echo "Wrapper script for the dangerous 'rm -rf'" | |
echo "Usage : $scriptName [folder to delete]" | |
exit 0 | |
fi | |
echo "$scriptName : Are you sure if you want to delete the following path? (y or n)" | |
printf "$(tput setaf 6) %s\n" "$@" | |
tput sgr 0 | |
ok=no | |
read ok | |
if [ ${ok:0} = 'y' ] ; then | |
for p in "$@" ; do | |
if [ "${p:0}" = '/' ] ; then | |
echo "$scriptName : Too Dangerous!!! (trying to delete a root level folder)" | |
echo "$scriptName : aborted..." | |
exit 1 | |
elif [ "$p" = '..' -o "$p" = '.' ] ; then | |
echo "$scriptName : Too Dangerous!!! (trying to delete \"$p\")" | |
echo "$scriptName : aborted..." | |
exit 1 | |
elif [ -f "$p" ] ; then | |
rm -rf "$p" | |
echo "$scriptName : \"$p\" (file) deleted..." | |
elif [ -d "$p" ] ; then | |
rm -rf "$p" | |
echo "$scriptName : \"$p\" (folder) deleted..." | |
else | |
echo "$scriptName : \"$p\" not found..." | |
fi | |
done | |
else | |
echo "$scriptName : aborted..." | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Rationale
rm -rf
is convenient, but way dangerous unless you are super careful!For example, say you wanted to do
rm -rf ../usr
, but you typedrm -rf .. /usr
by accident! (Note a space between .. and /usr)The possibility that you mistakenly insert a space is not so high, however, funny things happen all the time day to day.
This script basically does
rm -rf
, namely deleting arbitrary files and folders (and all of their sub-contents), but it is a lot safer.It will abort the task when you (ACCIDENTALLY!) attempt to do the following things:
Also, it will wait for your confirmation before deleting anything.