Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

trash — A safer alternative to the rm Command

The rm is the most commonly used command in the Linux/Unix world. It’s used to delete files and directories. But the problem with the rm command is that it deletes the files and directories permanently. There’s no way to recover them once they’re deleted.

Worse yet, if you use it with the -rf flag, it will delete the files and directories recursively and forcefully. So, if you accidentally delete a file or directory using the rm command, you’re pretty much out of luck if you want it back.

The trash CLI tool

This is where an npm package called trash comes in handy. It’s a cross-platform (works on macOS (10.12+), Linux, and Windows (8+)) command-line tool that moves files and directories to the system trash instead of removing them permanently. It’s like the rm command but with a safety net.

To use it, you need to install it globally using the following command.

$ npm install --global trash-cli

Once installed, you can use it like so.

$ trash <file|directory>

For instance, if you want to delete a file called foo.txt, you can do it like so.

$ trash foo.txt

Or if you want to delete files based on a pattern, you can do it like so.

$ trash '*.txt'

Recovering files

So, once you’ve deleted the files using the trash command, you can recover them from the respective trash folder of the operating system you’re using.

For instance, if you’re on macOS, you can recover the files from the ~/.Trash folder. Similarly, if you’re on Linux, you can recover the files from the ~/.local/share/Trash folder.

On Windows, you can recover the files from the Recycle Bin.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?