tags:

views:

1386

answers:

3

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.

A: 

This sounds like a good place for a try...on error block. I believe the following should do what you want:

tell application "Finder"
   try
      open "File:Path:To:the:script"
   on error
      open "File:Path:To:the:Anotherscript"
   end try
end tell
Seth Johnson
I used the exact code above but it still fails sometimes.
+1  A: 

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.

Philip Regan
+2  A: 

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"

HTH

stib