RonPringadi RonPringadi - 1 year ago 120
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:


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 Source

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

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

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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download