Bash 检查文件/文件夹是否存在,如果存在,将其删除,如果不存在,则显示消息。。。AppleScript中的问题

Bash 检查文件/文件夹是否存在,如果存在,将其删除,如果不存在,则显示消息。。。AppleScript中的问题,bash,macos,shell,terminal,applescript,Bash,Macos,Shell,Terminal,Applescript,使用此代码,当名为“new”的文件/文件夹不在桌面上时,我会收到预期的“No file”警报,但是当文件在那里时,它不会删除它,而是给我一个脚本错误。有没有关于如何解决这个问题的建议?很多thnx! AppleScirpt中有两种样式路径,即HFS和POSIX。你可以这样做 set theFile to (("Macintosh SSD:private:var:root:Desktop:new") as text) set status to false as boo

使用此代码,当名为“new”的文件/文件夹不在桌面上时,我会收到预期的“No file”警报,但是当文件在那里时,它不会删除它,而是给我一个脚本错误。有没有关于如何解决这个问题的建议?很多thnx!



AppleScirpt中有两种样式路径,即HFS和POSIX。你可以这样做

set theFile to (("Macintosh SSD:private:var:root:Desktop:new") as text)
 set status to false as boolean

tell application "Finder" to if exists theFile then set status to true
 if status is true then
  delete theFile
else
 display alert "No file."
end if
两个问题:

  • 您正在检查文字字符串(文本),而不是文件
  • delete
    行需要告诉
    Finder
    执行此任务
这是一个更简单的脚本版本<代码>桌面路径始终指向当前用户的桌面文件夹

--set theFile to "Macintosh HD:Users:mac:Downloads:1024.png"
set theFile to POSIX file "/Users/mac/Downloads/1024.png"

set status to false as boolean

tell application "Finder" to if exists theFile then set status to true
if status is true then
    display alert "file exist"
else
    display alert "No file."
end if
除了最可能出现的问题外,您没有足够的访问权限写入/private/var/…

只需尝试:

set theFile to (path to desktop as text) & "new"
tell application "Finder" 
   if exists file theFile
      delete file theFile
   else
      display alert "No file."
   end if
end tell

我在登录根用户帐户时运行此操作。如果我需要从其他用户桌面而不是我登录的帐户桌面删除某些内容,该怎么办?我认为命令“path to desktop”只适用于我当前所在的帐户。然后我建议使用shell。使用shell就可以了。
set daFile to "/Macintosh SSD/private/var/root/Desktop/new"
try
    do shell script "ls \"" & daFile & "\""
on error
    display dialog "File Does Not Exist!!!"
end try