Applescript to check if files exist

China☆狼群 提交于 2019-12-11 10:58:53

问题


I want to check if any of particular files (dictionaries) exist in "/Library/Dictionaries/". Here is my Applescript code lines:

tell application "Finder"
try
    set theFolder to ("/Library/Dictionaries/")
    set fileNames to {"dict1.dictionary", "dict2.dictionary", "dict3.dictionary", "dict_n.dictionary"}
on error
    set fileNames to false
end try
if fileNames is not false then
    try
        display dialog "You have already got the dictionary."
    end try
end if
end tell

Weirdly, the message You have already got the dictionary. is always shown albeit no listed files exist.

My purpose is to check if any of the listed files exits, and if one or more of them exits then the message is to be displayed.

In fact, this script will be run as a Unix bash script via /usr/bin/osascript, so I will be very grateful if you can help with either Apple script or Bash script.


回答1:


Try

   set theFolder to (path to library folder as text) & "Dictionaries:"
set fileNames to {"Apple Dictionary.dictionary", "dict2.dictionary", "dict3.dictionary", "dict_n.dictionary"}

set dict to {}
repeat with aFile in fileNames
    tell application "Finder"
        if exists file (theFolder & aFile as text) then set end of dict to aFile & return
    end tell
end repeat

if dict ≠ {} then display dialog "You have the following dictionaries installed:" & return & dict



回答2:


Another method is to try to coerce a file object to an alias:

set p to (system attribute "HOME") & "/Desktop/test.txt"
try
    POSIX file p as alias
    true
on error
    false
end try

Note that this results in an error when as alias is evaluated:

"/non-existing/path"
tell application "Finder" to exists POSIX file result as alias

This doesn't result in an error:

POSIX file "/non-existing/path"
tell application "Finder" to exists result


来源:https://stackoverflow.com/questions/12297788/applescript-to-check-if-files-exist

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