Ceci n'est pas un blog
Moving files to trash from the Mac command line
Ever wished you could move files to the trash from the command line on the Mac? Here's how.
First, buy a Mac. Then
Option 1 (uses bash): add the following to your ~/.bash_profile
function rem { for b in "$@" do osascript -e "tell app \"Finder\" to delete POSIX file \"${PWD}/$b\"" done } |
Then type 'source ~/.bash_profile' in Terminal.
Or Option 2 (uses Python and gives slightly more meaningful error messages): make an executable file called 'rem' somewhere in your $PATH:
#! /usr/bin/python import os import sys if len(sys.argv) > 1: for arg in sys.argv[1:]: if os.path.exists(arg): os.system('osascript -e \'tell app "Finder" ' + 'to move the POSIX file "' + os.path.abspath(arg) + '" to trash\'') else: print "Error:", os.path.abspath(arg), "does not exist" else: print "usage: rem file(s)" print " move file(s) to Trash" |
Now, either way, to move 'blah.txt' to Trash, simply type 'rem blah.txt'. Wildcards and lists of files are permitted. You even get the sound effects!
(This makes use of Applescript and works for me on OS X Tiger and Leopard. Thanks to kw for pointing out the problem with Option 1 and leading me to think of an alternative - 3 July 2008. And thanks for icke for showing me how to make the bash version work all the time - 6 Nov 2008.)
| Print article | This entry was posted by Anthony on 8 Jan 2008 at 4.58 pm, and is filed under Computing. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
I live in York and I
about 4 years ago
Is there a way to make this work on files with spaces in the names?
about 4 years ago
Hi - you're right, it doesn't work when the name has spaces in. There's probably a solution, but I don't have one at the moment I'm afraid...
Cheers,
Anthony
about 4 years ago
Hi again - I've found a solution using Python and added it to the original post.
about 4 years ago
No spaces problem with:
function trash {
osascript -e "tell application \"Finder\"" -e "delete POSIX file \"${PWD}/$*\"" -e "end tell"
}
about 4 years ago
Thanks - that solves the spaces problem, but it doesn't let you delete several files at once ('trash *.txt' or 'trash file1 file2' etc). I'm sure there's a way to do it though...
about 4 years ago
Simply use "$@" (with double quotes!) in your for loop.
about 4 years ago
Excellent - thanks! I've re-written the bash version accordingly.