用于检查文件是否存在的Applescript

时间:2012-09-06 10:13:42

标签: bash unix applescript

我想检查“/ Library / Dictionaries /”中是否存在任何特定文件(词典)。这是我的Applescript代码行:

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

奇怪的是,尽管没有列出的文件存在,但始终会显示消息You have already got the dictionary.

我的目的是检查是否有任何列出的文件退出,如果其中一个或多个退出,则显示该消息。

实际上,这个脚本将通过/usr/bin/osascript作为Unix bash脚本运行,所以如果你能帮助Apple脚本或Bash脚本,我将非常感激。

2 个答案:

答案 0 :(得分:2)

尝试

   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

答案 1 :(得分:1)

另一种方法是尝试将文件对象强制转换为别名:

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

请注意,评估as alias时会出错:

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

这不会导致错误:

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