What’s the real point of the -f option on rm

coreutilsoptionsrm

By reading the GNU coreutils man page for rm, one of the options is -f, which according to the manual,

-f, --force
          ignore nonexistent files and arguments, never prompt

Now, I made some tests and show that indeed if I use something like

rm -f /nonexisting/directory/

it won't complain.

What can someone really gain from such an option?

Plus the most common examples of "deleting directories" using rm is something
like

 rm -rf /delete/this/dir

The -r option makes sense, but -f?

Best Answer

I find that the man page lacks a little detail in this case. The -f option of rm actually has quite a few use cases:

  • To avoid an error exit code
  • To avoid being prompted
  • To bypass permission checks

You are right that it's pointless to remove a non-existent file, but in scripts it's really convenient to be able to say "I don't want these files, delete them if you find them, but don't bother me if they don't exist". Some people use the set -e in their script so that it will stop on any error (to avoid any further damage the script can cause), and rm -rf /home/my/garbage is easier than if [[ -f /home/my/garbage ]]; then rm -r /home/my/garbage; fi.

A note about permission checks: to delete a file, you need write permission to the parent directory, not the file itself. So let's say somehow there is a file owned by root in your home directory and you don't have sudo access, you can still remove the file using the -f option. If you use Git you can see that Git doesn't leave the write permission on the object files that it creates:

-r--r--r-- 1 phunehehe phunehehe 62 Aug 31 15:08 testdir/.git/objects/7e/70e8a2a874283163c63d61900b8ba173e5a83c

So if you use rm, the only way to delete a Git repository without using root is to use rm -rf.

Related Question