Safely remove directory with unknown contents

I have a directory /usr/local/foo, which I need to remove. This is going to be part of a script, which needs to be run as root. I'm mainly worried that the directory, which contains things that users can edit, could contain something that causes a simple "rm -rf /usr/local/foo" to accidentally delete other things. For example, if they managed to symlink foo to point to /dev or something and rm followed it.

I would like the directory gone, along with whatever is in it. This includes user files, symlinks, and everything else. However, I would like it to not delete /dev if some malicious user has symlinked foo to /dev.

System: Ubuntu and FreeBSD and OSX


If /usr/local/foo might contain user files, or your files, modified by the user, here's what to do:

Provide your script with a list of the filenames you want to delete (/usr/local/foo/{file1,old.txt} and a method of checking for user modifications. Checksums (man md5sum shasum) or file modification dates (man stat) are but two of the many methods you could use. Use bash's [[ -f $filename ]] test to ensure the "file" you're deleting is a file, not a link, subdirectory or whatever. (man bash)

Delete (man rm) the files on your list that pass the "unmodified" test.

Then, take advantage of rmdir's refusal to delete non-empty directories (man rmdir) with

rmdir /usr/local/foo

Ignore the error message and error status. If /usr/local/foo was empty, it's gone. If it had remaining files, it's not gone.