Skip to content

Instantly share code, notes, and snippets.

@suewonjp
Last active June 7, 2016 08:32
Show Gist options
  • Save suewonjp/bd54db6c959c47b81c0fd9583aeba340 to your computer and use it in GitHub Desktop.
Save suewonjp/bd54db6c959c47b81c0fd9583aeba340 to your computer and use it in GitHub Desktop.
[Bash tip] Safer 'rm -rf' command
#!/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
@suewonjp
Copy link
Author

suewonjp commented Jun 7, 2016

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 typed rm -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:

  • rmrf.sh /tmp (folder/files starting with a slash)
  • rmrf.sh .. (the parent directory)
  • rmrf.sh . (the current directory)

Also, it will wait for your confirmation before deleting anything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment