Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppleScript: If a file does not exist

Tags:

applescript

I need some way to determine if a particular file exists. If it exists do one script if not then do another script. Here was my logic in applescript:

If exists "File:Path:To:theFile"

tell application "Finder"
open "File:Path:To:the:script"
end tell

else

tell application "Finder"
open "File:Path:To:the:Anotherscript"
end tell

end if

The only problem is that sometimes when i use the above logic the script fails saying can't find the file. I need a full proof, never fails way to see if a file exists. I'm open to using the terminal, or applescript. I'm sure someone has run into this before but I have looked all over the web for an answer but could not find one.


2 Answers

In your original code you're giving the exists function a string, rather than a file, even though it's the path to a file. You have to explicitly give it a file, or it treats it the same as if you had tried to do

exists "god"

or

exists "tooth fairy"

The exists command won't know what you're talking about. You could use

return exists alias "the:path:to:a:file" 

but aliases don't work unless the file actually exists, so a non-existent file will create an error. You could of course catch the error and do something with it, but it's simpler to just give the exists function a file object. File objects belong to the Finder application, so:

return exists file "the:path:to:a:file" of application "Finder"
like image 169
stib Avatar answered Aug 18 '26 17:08

stib


I use the following to see if an item in the Finder exists:

on FinderItemExists(thePath)
    try
        set thePath to thePath as alias
    on error
        return false
    end try
    return true
end FinderItemExists

I think what you're missing is conversion of the path to an alias.

like image 44
Philip Regan Avatar answered Aug 18 '26 15:08

Philip Regan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!