Trashing (from) the Command Line

|

I’m a command line kinda guy. Always have been, and probably always will be. The GUI does have some advantages, though. For example, the Finder in Mac OS X moves files to the trash when deleting them, so you get a chance to resurrect them before actually removing them.

The Mac OS X command line is missing any way to move files to the trash, though. Sure there have been shell scripts ([1], [2], [3]) to move files to the trash, but they always have some limitations or annoyances. These solutions try to simulate how the Finder moves files to the trash, but usually miss a few details. Enter osx-trash.

osx-trash manipulates the Mac OS X trash from the command line, just like the Finder does. It uses AppleScript via Scripting Bridge on top of RubyCocoa to communicate with the Finder. You can move files to the trash, empty the trash, and list items currently in the trash.

osx-trash requires Mac OS X 10.5, Leopard. To install, use the gem command:

% sudo gem install osx-trash

You can also download the gem and other distributions from the RubyForge project page. Online documentation can be found on the Rubyforge home page.

Unfortunately, I don’t know of a way to have the gem require a specific version of Mac OS X. This means the gem will install on earlier versions of Mac OS X, and even non-Mac OS X systems, but it won’t work. If someone knows of a way to modify the gem specification to require OS X 10.5, please contact me.

The package comes with a command line program called trash. Here’s a simple example:

% touch foo bar baz
% trash -l
% trash foo ba*
% trash -l
/Users/dave/.Trash/foo
/Users/dave/.Trash/bar
/Users/dave/.Trash/baz
% trash -e
% trash -l

Using Finder’s AppleScript has a number of benefits compared to shell scripts that just move files to ~/.Trash. First, it creates unique names when there are collisions:

% touch foo
% trash foo
% touch foo
% trash foo
% trash -l
/Users/dave/.Trash/foo
/Users/dave/.Trash/foo 20-38-20

It also handles trashes on different volumes properly:

% touch foo
% trash foo
% touch /Volumes/DiskImage/bar
% trash /Volumes/DiskImage/bar
% trash -l
/Users/dave/.Trash/foo
/Volumes/DiskImage/.Trashes/501/bar

The project page is the permanent home for this project.

blog comments powered by Disqus

About this Entry

This page contains a single entry by Dave published on May 24, 2008 10:26 AM.

Invoke on Main Thread was the previous entry in this blog.

Suppressing Scripting Bridge Warnings is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Links

Powered by Movable Type 4.1