Lesson 8: rm Command
In this lesson, you'll learn how to use the rm command to remove files and directories in Linux.
The rm command is a UNIX and Linux command-line utility for removing files or directories on a Linux system.
It is also one of the most frequently used commands, but also one of the most dangerous, as we'll see later in this lesson.
By default, rm only removes files specified on the command line immediately. It does not remove directories unless you pass the right option.
Syntax:
rm [OPTIONS] FILE/DIRECTORY
Options:
| Option | Description |
|---|---|
| -r or -R | Remove directories and their contents recursively |
| -i | Prompt for confirmation before every removal |
| -f | Force removal - never prompt, ignore nonexistent files |
| -v | Verbose - print the name of each file as it is removed |
| --help | Display help information and exit |
| --version | Output version information and exit |
1. Remove a File
The most basic usage of rm command removes the specified file immediately without any confirmation.
rm tecmint.txt
2. Remove Multiple Files
To remove multiple files at once, specify the filenames one by one, or use a pattern to remove multiple files in one go.
# Using filenames
rm tecmint.txt fossmint.txt
# Using a pattern
rm *.txt
3. Remove a Directory
To remove a directory and all its contents, such as subdirectories and files, use the -r or -R flag, which tells rm to delete recursively.
rm -r tecmint_files/
Without -r, rm will refuse to remove a directory and return an error.
4. Remove a File with Confirmation
To prompt for confirmation before deleting, use the -i option. You'll be asked to confirm each deletion before it happens.
rm -i tecmint.txt
Output:
rm: remove regular file 'tecmint.txt'? y
5. Remove a Directory with Confirmation
To prompt for confirmation while deleting a directory and all its subdirectories, combine -R and -i.
rm -Ri tecmint_files/
rm will ask for confirmation for each file and subdirectory before removing it.