0

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

2
  • Installing and running Midnight Commander for visual inspection with then removal would be safer.
    – N0rbert
    May 27 at 5:45
  • 1
    Do not worry. rm will always delete the actual contents of the folder only. It will only remove a symlink itself, never the contents that the symlink points to.
    – vanadium
    May 27 at 10:05
3

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.

1
  • Note that this is not the answer to the question I asked. I did my best to specify that I don't care about what is in the folder, if a user put something there I want to erase it anyway. What I wanted to know was how to make rm not follow symlinks, hard links, or anything else.
    – Michael
    May 30 at 2:54
0

The command I was looking for was

rm -fr --one-filesystem foo

rm does not follow symlinks, and will just unlink the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.