Published at
Updated at
Reading time
2min

Wes Bos has advocated using the trash-cli instead of the rm command this week.

The reasoning: rm is unrecoverable. Once you remove files or directories using rm, they're gone. Ergo, you can bring yourself into real trouble using rm.

I assume one could do some wild forensic stuff to restore bits and bytes on your hard drive, but the deleted files have to be very important to go this route.

trash can help out here! The command doesn't delete files but moves them to your operating system's trash directory. When you then accidentally delete something important, head over to your lovely bin icon and recover files from there!

But here's the kicker: installing the global trash-cli package comes with 829 dependency files. Markdown, JavaScript, JSON and license files are all at your service, making up a whopping 4.3MB heavy node_modules directory.

Sure, 4 MB isn't an issue for me on my developer machine. And the command runs fast enough to protect me and my fat fingers from self-destruction. But still, that's a lot of dependency code to move files into another directory, isn't it?

A native trash CLI function

Liran Tal thought the same and shared a nifty four-liner giving you all of trash's functionality.

trash() {
  echo "[x] moving files to trash..."
  mv "$@" "$HOME/.trash"
}

I played around with Liran's function and adjusted it also to support multiple files.

# โœ… globs          โ€“ `trash file-*-.txt`
# โœ… directories    โ€“ `trash directory`
# โœ… multiple files - `trash file-1 dir-1 file-2`
function trash() {
  echo "๐Ÿ—‘๏ธ  Moving files to trash..."

  for var in "$@"
  do
    mv "$var" "$HOME/.trash"
  done
}

So far, my new trash command has been working great. I'll let you know when I'll discover any issues!

Disclaimer: I only tested this shell function in my environment: macOS and ZSH.

Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 7 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles