Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applescript testing for file existence

OK, I thought this would be a simple one, but apparently I'm missing something obvious. My code is as follows:

set fileTarget to ((path to desktop folder) & "file$") as string

if file fileTarget exists then
    display dialog "it exists"
else
    display dialog "it does not exist"
end if

Easy right? Unfortunately, when I run the script it returns the error

Can’t get file "OS X:Users:user:Desktop:files$".

It doesn't matter if the file exists or not, this is the same error I get. I've tried a dozen different things but it still stumps me.

like image 224
EightQuarterBit Avatar asked Aug 12 '10 15:08

EightQuarterBit


2 Answers

I use this subroutine to see if a file exists or not:

on FileExists(theFile) -- (String) as Boolean
    tell application "System Events"
        if exists file theFile then
            return true
        else
            return false
        end if
    end tell
end FileExists

Add salt to taste.

like image 129
Philip Regan Avatar answered Oct 14 '22 02:10

Philip Regan


It is easy except "exists" is a Finder or System Events command. It's not a straight applescript command. As such you must wrap it in a tell application code block. FYI: here's another way that doesn't require an application. It works because when you coerce a path to an "alias" it must exist otherwise you get an error. So you could do the following.

set fileTarget to (path to desktop folder as text) & "file$"

try
    fileTarget as alias
    display dialog "it exists"
on error
    display dialog "it does not exist"
end try

NOTE: you have an error in your code. You're using the & operator to add strings but you're doing it wrong although you're getting the right answer by luck. When you use the & operator, each object on either side of the operator must be a string. "path to desktop folder" is not a string so we first must make that a string and then add the string "file$" to it. So do it like this...

set fileTarget to (path to desktop folder as text) & "file$"
like image 7
regulus6633 Avatar answered Oct 14 '22 00:10

regulus6633