Search code examples
applescriptfilepathfinder

Get filepath of file in Finder


I want to get the filepath of the front file in the Finder, such as /Users/user/Downloads/file.png and I am very confused with the way macOS and AppleScript handle file paths, POSIX with slashes and natively with colons. I tried both of these:

tell application "Finder"
    set temp to selection
    repeat with i from 1 to length of temp
        set the_item to item i of temp
        
        set item_posix to the_item as POSIX file
        set the_result to POSIX path of item_posix -- returns only the file's name and extension
        
        return get the path of the_item -- returns an error
    end repeat
end tell

I once succeeded and it was so convoluted with as file and as alias that I can't remember how it worked.

How can I get the filepath of the front file in the Finder?

Update: I'm interested in a single path for the sake of the syntax and I can handle multiple paths with a loop.


Solution

  • With the inuxmint-20-cinnamon-64bit.iso files selected in the Downloads folders in Finder, here are some examples:

    This command:

    tell application "Finder" to get selection
    

    Result:

    --> {document file "linuxmint-20-cinnamon-64bit.iso" of folder "Downloads" of folder "me" of folder "Users" of startup disk}
    

    This command:

    tell application "Finder" to get selection as alias
    

    Result:

    -> {alias "Macintosh HD:Users:me:Downloads:linuxmint-20-cinnamon-64bit.iso"}
    

    This command:

    tell application "Finder" to set aliasItemName to selection as alias
    

    Result:

    --> {alias "Macintosh HD:Users:me:Downloads:linuxmint-20-cinnamon-64bit.iso"}
    

    These commands:

    set posixPathName to POSIX path of aliasItemName
    return posixPathName
    

    Result:

    "/Users/me/Downloads/linuxmint-20-cinnamon-64bit.iso"
    

    Note that set posixPathName to POSIX path of aliasItemName is done outside of the context of Finder as it does not understand POSIX path as it's a part of Standard Additions, not Finder.