Author: Dave McKay / Source: How-To Geek
The rm
and rmdir
commands delete files and directories on Linux, macOS, and other Unix-like operating systems. They’re similar to the del
and deltree
commands in Windows and DOS. These commands are very powerful and have quite a few options.
It is important to note that files and directories deleted using rm
and rmdir
do not get moved to the Trash. They are immediately removed from your computer. If you accidentally delete files using these commands, the only way you’ll be able to restore them is from a backup.
How to Remove Files with rm
The simplest case is deleting a single file in the current directory. Type the rm
command, a space, and then the name of the file you want to delete.
rm file_1.txt
If the file is not in the current working directory, provide a path to the file’s location.
rm ./path/to/the/file/file_1.txt
You can pass more than one filename to rm
. Doing so deletes all of the specified files.
rm file_2.txt file_3.txt
Wildcards can be used to select groups of files to be deleted. The *
represents multiple characters and the ?
represents a single character. This command would delete all of the png image files in the current working directory.
rm *.png
This command would delete all files that have a single character extension. For example, this would delete File.1 and File.2, but not File.12.
rm *.?
If a file is write-protected you will be prompted before the file is deleted. You must respond with y
or n
and press “Enter.”
To reduce the risk of using rm
with wildcards use the -i
(interactive) option. This requires you to confirm the deletion of each file.
rm -i *.dat
The -f
(force) option is the opposite of interactive. It does not prompt for confirmation even if files are write-protected.
rm -f filename
How to Remove Directories with rm
To remove an empty directory, use the -d
(directory) option. You can use wildcards (*
and ?
) in directory names just as you can with filenames.
rm -d directory
Providing more than one directory name deletes all of the specified empty directories.
rm -d directory1 directory2 /path/to/directory3
To delete directories that are not empty, use the -r
(recursive) option. To be clear, this removes the directories and all files and sub-directories contained within them.
rm -r directory1 directory2 directory3
If a directory or a file is write-protected, you will be prompted to confirm the deletion. To delete directories that are not empty and to suppress these prompts, use the -r
(recursive) and -f
(force) options together.
rm -rf directory
Care is required here. Making a mistake with the rm -rf
command could cause data loss or system malfunction. It’s dangerous, and caution is the best policy. To gain an understanding of the directory structure and the files that will be deleted by the rm -rf
command, use the…
The post How to Delete Files and Directories in the Linux Terminal appeared first on FeedBox.