RonPringadi RonPringadi - 27 days ago 7
Linux Question

Safe recursive delete in bash

Is there a way to check if the supplied path either by user input or some self-detect-mechanism safe to be deleted in bash scripting?

For example:

rm -rf $SOMELOCATION


Obviously I don't want SOMELOCATION to be any of / /var /etc /home /usr /opt /root or some important directories.

Is there a way to prevent such incident in bash without iterating all those directory above (and possibly more important directory)?

Is there something like isSystemDirectory function return true or false? :-)

Answer

No; you need to check the value of SOMELOCATION before you use it as the argument to rm.

case $SOMELOCATION of
  /|/var|/etc|/home|/usr|/opt|/root) echo "Will not delete $SOMELOCATION" ;;
  *) rm -rf "$SOMELOCATION ;;
esac

Permissions allow rm to fail, but since root essentially has permission to do anything, it is simply up to you to take appropriate care when running any command as root. (Or at the very least, to have an up-to-date backup available to recover from a mistake.)

Comments