How to remove files and directories in Linux
Linux includes two commands that you can use to delete files and directories: rm (remove) and rmdir (remove directory).
rm command to remove a file
The basic syntax of a “rm” command is as follows:
# rm [options] file-list
The rm utility removes hard and/or symbolic links to one or more files. When you remove the last hard link to a file, the file is deleted. Let’s remove a file using rm command:
# rm file01
You might be asked by system to confirm the deletion of the file:
remove file01 (y/n)?
Alternatively, you can also use the -i option, which runs the rm command interactively. So each file will be deleted only after your confirmation.
rm command options
There are several options that can be used with rm commands. Some of the most commonly used options are listed below:
|–interactive -i||Provides an interactive prompt before removing file.|
|–recursive -r||Deletes the contents of the specified directory, including all its subdirectories, and the directory itself|
|–verbose -v||Displays the name of each file as it is removed.|
|–force -f||Without asking for your consent, removes files for which you do not have write access permission. This option also suppresses informative messages if a file does not exist.|
rm command Tips
1. The -i or –interactive=always options allow review and confirmation before each entry being deleted. Answering n rather than y to the prompts (Enter must be pressed after y or n) will either skip deleting some files or skip entire directories.
2. -I or –interactive=once prompts only once before removing more than three files, or when removing recursively, whereas -i prompts for each and every file or directory.
rmdir command to remove directories
The rmdir command is used to delete empty directories. This command will fail if the directory is not empty (use rm -r to delete a directory and all the files within the directory). You can use the “rm -fr” to remove directories that are not empty.
The basic syntax of a “rmdir” command is as follows:
# rmdir [options] directory-list
The directory-list is a list of pathnames of empty directories that rmdir removes.
Example for “rmdir” command:
# rmdir /tmp/dir01
rmdir command options
Unlike rm command, rmdir command has fewer options.
|–ignore-fail-on-non-empty||Suppresses the message rmdir normally displays when it fails because a directory is not empty.|
|–verbose -v||Displays the names of directories as they are removed.|
|–parents -p||Removes a hierarchy of empty directories.|
Remove files and directories recursively
Use the rm utility with the –r option if you need to remove directories that are not empty, together with their contents. For example:
# rm -fr /tmp/dir01
The -f option makes the rmdir command continue silently even when a file or directory to be deleted is not present.