Everything is a file in Linux including a directory. A directory is just a group of files.

There are primarily two commands that delete files and directories in linux:

  • rm
  • rmdir

Delete an Empty Directory

The rmdir command is used to delete an empty directory in linux.

For example, the following code deletes the “images” directory which has no files inside it:

$ rmdir images/

We can also use the rm command with the -d option to delete an empty directory:

$ rm -d images/

If we tried the above command on a non-empty directory, we would get:

$ rmdir images/

rmdir: images/: Directory not empty

Delete a Directory and Its Contents

To delete a directory with all it’s content recursively use the rm command with argument -r.

$ rm -r images/

You can also delete a directory and all it’s contents forcefully with the -rf argument.

$ rm -rf images/

Delete a File

To delete a file in linux, simply use the rm command:

$ rm cat.gif

Delete a File Forcefully

To force delete a file use the -f option with the rm command:

$ rm -f cat.gif

Prompt Before Deleting a File or Directory

If you want to be prompted for confirmation before deleting a file or directory, use the -i option with the rm command:

$ rm -i cat.gif

remove cat.gif? y

Be Verbose When Deleting

To see an output of the deleted files use -v option:

$ rm -v cat.gif


Delete Multiple Files

To delete multiple files in one operation, we use the * wildcard.

For example, the following code deletes all images with .gif extension:

ls images/
bird.png	cat.gif		dog.gif

rm *.gif

ls images/

Complete rm Usage

rm Syntax

rm [-dfiPRrvW] file ...

Table below shows the usage of the rm command with all of its options.

| Option | Description                                                                                                         |     |     |
| -d     | Attempt to remove directories as well as other types of files.                                                      |     |     |
| -f     | Attempt to remove the files without prompting for confirmation, regardless of the file's permissions.               |     |     |
| -i     | Request confirmation before attempting to remove each file, regardless of the file's permissions                    |     |     |
| -P     | Overwrite regular files before deleting them.                                                                       |     |     |
| -R     | Attempt to remove the file hierarchy rooted in each file argument.                                                  |     |     |
| -r     | Same as -R                                                                                                          |     |     |
| -v     | Be verbose when deleting files, showing them as they are removed.                                                   |     |     |
| -W     | Attempt to undelete the named files. Currently, this option can only be used to recover files covered by whiteouts. |     |     |