How To Remove Files and Directories on Linux Terminal
In this tutorial, we will show you how to remove files and directories in the Linux terminal. Deleting files and folders is also one of the most essential. If you never get rid of anything, soon enough all those extra gigabytes will take a toll on your Linux system processing power, RAM, and hard drive, not to mention your digital life will resemble a dreadful episode of Hoarders.
This article assumes you have at least basic knowledge of Linux, know how to use the shell, and most importantly, you host your site on your own VPS. The installation is quite simple and assumes you are running in the root account, if not you may need to add ‘sudo
‘ to the commands to get root privileges.
Prerequisites
- A server running one of the following operating systems: Ubuntu or CentOS.
- It’s recommended that you use a fresh OS install to prevent any potential issues.
- A
non-root sudo user
or access to theroot user
. We recommend acting as anon-root sudo user
, however, as you can harm your system if you’re not careful when acting as the root.
Remove Files and Directories on Linux Terminal
- Remove Files with
rm
To remove (or delete) a file in Linux from the command line, use either the rm
(remove). 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.txt
You can pass more than one filename to rm. Doing so deletes all of the specified files:
rm file_1.txt file_2.txt
Be careful when using this command, as once a file is deleted, it cannot be recovered unless you have a backup.
- Remove Directories with
rm
To remove an empty directory, use the -d
(directory) option. You can use wildcards (*
) in directory names just as you can with filenames:
rm -d directory
More than one directory name deletes all of the specified empty directories:
rm -d directory directory1 /path/to/directory2
To delete directories that are not empty and to suppress these prompts, use the -r
(recursive) and -f
(force) options together:
rm -rf directory
- Remove Directories with
rmdir
In Linux, you can remove/delete directories with the rmdir
and rm
. The difference between rm
and rmdir
is that rmdir
can only delete directories that are empty. It will never delete files.
Delete a single directory in the current directory:
rmdir directory
Delete multiple directories:
rmdir directory1 directory2 directory3
Delete a directory not in the current directory by specifying the full path to that directory:
rmdir /path/to/directory
Deleting files and directories in Linux was made easy. Congratulations! You have successfully learned how to remove or delete all the files in a directory using the rm
command.
NOTE, be careful when using this command, as it will delete the entire directory and all of its contents permanently.