Permanently delete files via AppleScript

Nov 29, '07 07:30:00AM

Contributed by: tomote

Ever since switching to OS X from Windows, I've missed the convenience of being able to permanently delete files using Shift-Delete. In order to duplicate that functionality, I've written a short AppleScript that will delete the files selected in Finder instead of placing them in the trash.

set frontAppPath to (path to frontmost application) as string

if the frontAppPath ends with ":Finder.app:" then
  tell application "Finder"
    set selectionList to get selection as list
    set selectedCount to count items in selectionList
    
    if selectedCount > 0 then
      repeat with i from 1 to number of items in the selectionList
        set selectedItem to item i of the selectionList
        set selectedName to the name of selectedItem
        set homePath to (path to home folder) as string
        set trashPath to homePath & ".Trash:"
        set deletePath to trashPath & selectedName & ":"
        
        if not ((kind of selectedItem as string) is equal to "Volume") then
          if (selectedItem as string) contains ".Trash" then
            set posixPath to POSIX path of (selectedItem as string) as string
            do shell script "rm -rf \"" & posixPath & "\""
          else
            try
              deletePath as alias
              display dialog "Error: file named \"" & selectedName & "\" already exists in the Trash."
            on error
              try
                tell application "Finder" to delete selectedItem
                do shell script "rm -rf ~/.Trash/\"" & selectedName & "\""
              end try
            end try
          end if
        end if
      end repeat
    end if
  end tell
end if
The best way to use this script is to assign it to a shortcut key (e.g., shift-backspace) using a program like Spark.

Notes:
  1. The script first moves files to the trash before permanently deleting them. This prevents accidentally deletion of protected or system files.
  2. The script will not delete or remove files that have a duplicate filename already in the trash.
  3. It will not remove files which are not on the local hard drive.
  4. It will only launch if the foremost active window is Finder.
[robg adds: Beyond making sure the code compiles, I have not tested this script. However, if you intend to use this, please do all your testing on a copy of a copy of a non-critical file, and make sure that your backups are current. It should go without saying, but this is a potentially very dangerous hint -- use it incorrectly, and the file(s) you've chosen are gone for good with no recourse for recovery.]

Comments (7)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20071114065424440