Skip to content

Deleting Files and Folders with Bash

Bash, File Management, Command Line1 min read

In the world of command-line interfaces (CLI), Bash reigns supreme, providing robust tools for efficient file and folder management. Among its many features, file deletion is a very commonly used task.

Deleting Files

Deleting files in Bash is a straightforward process, thanks to the rm command, which stands for "remove." The basic syntax of the rm command is as follows:

1rm [options] [file(s)]
  • [options]: Optional flags that modify the behavior of the rm command.
  • [file(s)]: The name(s) of the file(s) you want to delete.

For instance, to delete a single file named example.txt, you would use the following command:

1rm example.txt

If you want to delete multiple files simultaneously, you can specify their names separated by spaces:

1rm file1.txt file2.txt file3.txt

Deleting Folders

Deleting folders in Bash follows a similar pattern to deleting files, but with an additional consideration. The rm command alone can only delete empty folders. However, to delete folders containing files and subdirectories, you need to employ the -r or -rf option, which stands for "recursive force."

The syntax to delete a folder is as follows:

1rm -r [folder(s)]

Or, for more forceful deletion (use with caution, as it will delete without asking for confirmation):

1rm -rf [folder(s)]

For instance, to delete an empty folder named docs, you would use:

1rm -r docs

To delete a folder named images along with all its contents (files and subdirectories), you would use:

1rm -rf images

Additional Options

The rm command provides various options to customize the deletion process according to your needs. Some commonly used options include:

  • -i: Interactive mode, which prompts you for confirmation before deleting each file.
  • -v: Verbose mode, which displays detailed information about the files being deleted.
  • --preserve-root: Prevents rm from running if the target directory is / or /etc.

These options can enhance control and safety when deleting files and folders, especially when dealing with sensitive or critical data.