rm Command – Does rm -rf * Delete Files Recursively from Current Directory?

recursiverm

I wanted to delete files and folder recursively from a particular folder so I ran this command from that folder

rm -rf *

I assumed it would delete all files/directories under the current directory recursively. Something bad happened after that (my server is down, not even getting ping response).

Best Answer

Don't forget the possibility that the server being unreachable after the rm command had nothing to do with that. It could be a coincidence!

Most likely though, the current working directory was not what you thought, when the command was issued.

Were you root when doing this?

This is what happens when issuing the command rm -rf *:

  1. The shell resolves the wildcard patterns (* in this case) to all files (including directories, symbolic links and device special files) that matches the used globbing pattern, in this case everything not beginning with a . Normally, these are sorted "alphabetically" by the shell.
  2. The shell then forks a new process and exec()s the first version of rm found in your $PATH, with -rf as the first argument, and the matched files, one by one as the consecutive arguments.

If the rm that was invoked was the standard rm command, it first parses the arguments, one by one, treating all arguments (including ones resulting from shell globbing) that begin with a - as options until it comes to an argument that does not begin with a - (except for commands using GNU getopt() that accept options after non-options), or one that is exactly --. Everything after that is considered file names.

In other words, if you had a file called (for example) --no-preserve-root in the current directory, that would have been interpreted as an option to rm, not as a file name to remove!

Be careful with wildcards (and with file naming). If you have a file called -r in the current directory, the command ls * would list the other files in reverse order, and not show the '-r' file.

In other words, if you had a file called --no-preserve-root, that would have been passed as an option to rm, not as a file name.

Use rm -rf -- * to prevent that from happening, and also remove the files beginning with -. Or simply use absolute or relative path names to make the filenames begin with something other than -, as in: rm ./--flagfile or rm /abs/path/to/--flagfile.

There is also a -i flag to rm that makes it prompt ("interactively") before removing anything.

Related Question