问题描述
我正在编写一个AppleScript,我想在其中插入一个子例程来删除指定的文件.我希望使用一个标志来控制将给定的文件移至回收站还是将其永久删除.
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.
实际上我的脚本如下:
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
现在我想知道这种情况是否正确,或者是否还有另一个我忽略的Finder命令或delete命令的参数,这样我就可以简化上面的脚本了?
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?
推荐答案
AppleScript是一种脾气暴躁的野兽,细节中常常有魔鬼.
AppleScript is a temperamental beast, and the devil is often in the details.
@adayzdone的答案提供了至关重要的指针-使用System Events
应用程序的delete
命令来实现永久性删除,找出确切的语法需要反复尝试:
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:
注意事项:此处理程序可同时处理文件和文件夹-将allowUndo
设置为false
的文件夹定位,因此永久删除该文件夹的整个子树.
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
在OS X 10.9.4上,我必须执行以下操作才能完成此工作:
On OS X 10.9.4 I had to do the following to make this work:
-
Finder
上下文:必须将POSIX file theFile
更改为theFile as POSIX file
(后缀形式)-不要问我为什么. -
System Events
上下文:使用提供的POSIX路径的"cast"alias
是对我有用的命令的唯一形式.
Finder
context: Had to changePOSIX file theFile
totheFile 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):
但是请注意,仅使用rm
仅适用于文件-如果您也希望将其扩展到文件夹,请使用rm -rf
代替-相同的 caveat将永久保留删除整个子树.
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
请注意使用quoted form of
,它可以安全地将文件路径传递到外壳,并正确编码字符(例如空格).
Note the use of quoted form of
, which safely passes the file path to the shell, encoding characters such as spaces properly.
这篇关于使用AppleScript删除文件以回收站或永久回收站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!