Delete files with AppleScript to recycle bin or permanently

白昼怎懂夜的黑 提交于 2019-12-06 08:35:24

问题


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?


回答1:


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.




回答2:


You can use System Events to permanently delete a file.



来源:https://stackoverflow.com/questions/24721329/delete-files-with-applescript-to-recycle-bin-or-permanently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!