Delete Files Using the Linux Command Line

Use 'rm' or 'trash-cli' to remove files from a shell prompt

As with so many tasks, Linux offers more than one way to get a job done, with each solution having varying pros and cons. The typical method of removing a file using a shell prompt entails the rm command, although the trash-cli command works, too.

The 'rm' Command

Most people use the rm command to delete files. The syntax of the rm command is as follows:

rm /path/to/file

Delete all the files in a folder and subfolders using the -R flag (to delete recursively) as follows:

rm -R /path/to/folder

The rm command is final. Files and folders removed by this method are generally not recoverable without special tools.

The 'trash-cli' Command

The trash-cli application provides a command-line trash can. It isn't usually installed by default with Linux, so install it from the repositories of your distribution.

To send a file to the trash can, use the following command:

trash /path/to/file
trash command in linux

The file is not fully deleted but instead sent to a trash can in the same way as the Windows recycle bin. If you supply the trash command a folder name, it sends the folder and all the files in the folder to the recycle bin.

How to List the Files in the Trash Can

To list the files in the trash, run the following command:

trash-list

The results returned include the original path to the file, and the date and time the files were sent to the trash can.

How to Restore Files From the Trash Can

To restore a file, use the following command:

trash-restore

You may, however, receive a command not found error if you run this command.

The alternative to trash-restore is restore-trash, as follows:

restore-trash

The restore-trash command lists all the files in the trash with a number next to each one. To restore a file, enter the number next to the filename.

How to Empty the Trash Can

The main issue with the trash can approach is that the deleted files take up drive space. If you are satisfied that everything in the trash can is no longer required, run the following command to empty the trash:

trash-empty

If you want to delete all the files that have been in the trash for a certain number of days, specify that number with the trash-empty command.

trash-empty 7