Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete files with AppleScript to recycle bin or permanently

I'm writing an AppleScript in which I want to insert a subroutine to delete specified files. With a flag I wish to control whether the given file is moved to the recycle bin or deleted permanently.

Actually my script looks like this:

on MyDeleteProc(theFile, allowUndo)
  if allowUndo then
    tell application "Finder" to delete POSIX file theFile
  else
    do shell script "rm " & theFile
  end if
end MyDeleteProc

Now I want to know if this case is correct so far or is there maybe another Finder command or a parameter for the delete command that I overlooked so I will be able to simplify the script above?

like image 478
altralaser Avatar asked Oct 23 '25 00:10

altralaser


2 Answers

AppleScript is a temperamental beast, and the devil is often in the details.

While @adayzdone's answer provides the crucial pointer - use of the System Events application's delete command to achieve permanent deletion, working out the exact syntax takes trial and error:

Caveat: This handler works with both files and folders - targeting a folder with allowUndo set to false therefore permanently deletes that folder's entire subtree.

on MyDeleteProc(theFile, allowUndo)
  if allowUndo then
    tell application "Finder" to delete theFile as POSIX file
  else
    tell application "System Events" to delete alias theFile
  end if
end MyDeleteProc

On OS X 10.9.4 I had to do the following to make this work:

  • Finder context: Had to change POSIX file theFile to theFile as POSIX file (postfix form) - don't ask me why.
  • System Events context: Using "cast" alias with the POSIX path provided is the only form of the command that worked for me.

That said, a little tweak to your original function would make it work, too (and unless you delete many files one by one, performance probably won't matter):

Note, however, that just using rm only works with files - if you wanted to extend it to folders, too, use rm -rf instead - the same caveat re permanently deleting entire subtrees applies.

on MyDeleteProc(theFile, allowUndo)
  if allowUndo then
    tell application "Finder" to delete theFile as POSIX file
  else
    do shell script "rm " & quoted form of theFile
  end if
end MyDeleteProc

Note the use of quoted form of, which safely passes the file path to the shell, encoding characters such as spaces properly.

like image 166
mklement0 Avatar answered Oct 25 '25 22:10

mklement0


You can use System Events to permanently delete a file.

like image 35
adayzdone Avatar answered Oct 25 '25 22:10

adayzdone