Home > Articles

  • Print
  • + Share This

Deleting Files and Directories

Removing files and directories is another common task when using Linux and should be performed with care. Deleted files and directories are irrevocably lost. This is a great reason to always maintain backups of important files or directories.

Deleting Files with the rm Command

The rm (remove) command is used to delete files and directories. You delete files by including a single filename or several filenames on the command line, like so:

$ rm sentmailJune1998 sentmailJuly1998 sentmailAugust1998

Use wildcards to delete multiple files:

$ rm *1998

The rm command with the -r (recursive) can also be used to delete files within a specified directory. If you attempt to delete a directory without this option, the rm command complains and quits. The -i (interactive) option elicits a prompt before deleting each file in the directory. This option is set up to be automatically included with rm on many machines. Conversely, the -f (force) option specifies that you do not want to be prompted for each file in the directory. It also suppresses error messages and warnings (so use it with caution). See the following example:

$ rm -ri sentmail/ 
rm: descend directory ´sentmail'? y 
rm: remove ´sentmail/sentmailJune1998'? y 
rm: remove ´sentmail/sentmailJuly1998'? y 
rm: remove ´sentmail/sentmailAugust1998'? y 
rm: remove directory ´sentmail'? Y 

Deleting Directories with the rmdir Command

You can remove directories by using the rmdir command.

$ rmdir homework/compsci/linux/kernal_hacking 
$ rmdir homework/compsci 
rmdir: homework/compsci: Directory not empty 

However, if any files or directories exist below the specified directory, you must move or delete those first.

Deleting Directories with the rm Command

The rm command can be used like the rmdir command to remove directories, but you must use the -r (recursive) option in conjunction with the -f (force) option to do so. This combination of options removes files and directories without asking for confirmation. Here is an example:

$ rm -rf homework

Using the rm command while root can be dangerous

The rm command, used with the -fr (recursive and force) options, is especially dangerous to use if you're running as the root operator. A single command line can wipe out your system. Use the -fr option with caution; this unconditional delete destroys all files and directories in its path. Avoid using this option while logged in as the root operator unless you're absolutely certain of the files and directories you want to delete.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.