Bryan Dunphy
Bryan Dunphy

Reputation: 851

Can Applescript be used to tell whether or not a directory (path) exists?

I've got some Applescript code that switches to a specified directory by KEYSTROKEing the path into the "Go To" dialog.

Regretfully, this dialog does NOT raise an error if the requested directory does not exist?! It just goes as far as it can along the path and then DUMPS THE NONEXISTENT PATH FRAGMENT into the default text field of whatever window is under it!

Example: given "~/Music/nonexistent" it would switch to the Music folder in the user's home folder then 'type' "nonexistent" into the underlaying window's default text field if it has one.

Consequently, I need to know how to find out if a given path already exists or not from Applescript.

Upvotes: 1

Views: 1151

Answers (2)

BK201 Freelance
BK201 Freelance

Reputation: 21

What about something like this?

set theFolder to "path:to:the:Folder:" --your folder/path


if FolderExists(theFolder)=true then -- HERE YOU DON'T have to put exists again, it's already check in the handler FolderExists(theFolder)

      display dialog "Exists " & theFolder & " !"

else

      display dialog "Missing " & theFolder & " !"

end if

--handler for checking if exists theFolder/thePath

    on FolderExists(theFolder) -- (String) as Boolean
        tell application "System Events"
            if exists folder theFolder then
                return true
            else
                return false
            end if
        end tell
    end FolderExists

Upvotes: 0

vadian
vadian

Reputation: 285072

In AppleScript you can simply check if a path exists by coercing the path to an alias specifier. If the path does not exist an error is thrown

Further you have to expand the tilde programmatically. The handler returns a boolean value.

on checkPathExists(thePath)
    if thePath starts with "~" then set thePath to POSIX path of (path to home folder) & text 3 thru -1 of (get thePath)
    try
        POSIX file thePath as alias
        return true
    on error
        return false
    end try
end checkPathExists

set pathisValid to checkPathExists("~/Music/nonexistent")

Alternatively use System Events, but sending an Apple Event is a bit more expensive:

set thePath to "~/Music/nonexistent"
tell application "System Events" to set pathisValid to exists disk item thePath

Upvotes: 3

Related Questions