In this tutorial, we will learn how to delete files and folders using the command line on Linux. This tutorial is compatible with all Linux distributions, so it works in the same way on Ubuntu, Debian, CentOS, AlmaLinux, Rocky Linux, etc. So, let’s get started.
Delete a File on Linux
In Linux rm command is used to remove files and folders on the command prompt. Navigate to that specific directory where the file exists that you want to remove. The rm command is basically the equivalent of the del command on Windows. Specify the location otherwise, it will start looking in the current working directory. I have a file under the /tmp/ folder which I want to delete. To delete the desired file open up the terminal and type the following command:
# rm file.txt
Be careful, while files and folders from Linux because once deleted, they can’t be rolled back. For this use –i, it will ask you for confirmation before deleting the file:
# rm –i file.txt
If you do not want a confirmation message for deletion, use the following command:
# rm –f file.txt
It will not prompt the confirmation message.
Delete Multiple Files on Linux
To delete multiple files on Linux, we can use the same command rm.
# rm file.txt file1.txt file2.txt
This will delete all the files.
Delete Directory on Linux
To delete a directory on Linux, the same command is used. But you need to add -r and -f options to delete a directory.
# rm –rf /data
But be careful, this deletes the directory recursively with all files and folders inside. You can use the above without -f, as it will not prompt for confirmation. -r option is used for deleting the directory.
If you just want to remove a directory that is empty, use this command instead:
rmdir /data
The command will show an error in case the directory is not empty.
Summary
- In all Linux distributions, rm command is used to delete the files and folder.
- If -i is used with rm, it will prompt for the confirmation before deleting.
- If -r is used with rm, it will delete the directory.