Search code examples
bashmacosapplescriptautomatorfinder

Use highlighted file in Finder as Bash variable (Applescript, macOS 10.13)


I want to set up an applet for archiving my files in non-standard formats (e.g. non .zip/.cpgz/.tar) with only the use of Applescript and the command line versions of each format's respective tool. The last thing I need to figure out is how to get the path of the currently highlighted file in Finder via Applescript, so that I can pipe it to bash.

I've searched around a bit and can't seem to find an answer to this via search engine, or this forum. I have found and still find that Apple's documentation has about a 40/60 chance of being too sparse and/or outdated, or even simply nonexistent for any given subject, so I opt not to use it when possible. Please don't just link to an Apple documentation page, Real-world examples are always appreciated.

The target platform is macOS 10.13.2, Automator 2.8, Applescript 2.7.


Solution

  • There is more then one way to do it and also depends on how may Finder items are selected. Here's an example if only one item is selected in Finder:

    set theTarget to POSIX path of (application "Finder"'s selection as string)
    

    Or, if the pathname has spaces, use:

    set theTarget to quoted form of POSIX path of (application "Finder"'s selection as string)
    

    Sans the shown examples, the other ways can depend on how/where it falls in the rest of your code and whether or not more then one item is selected in Finder, however this is a place to start.


    BTW If you're doing this AppleScript from bash, not Script Editor where the other examples were run, then using osascript in bash to run the same example AppleScript code shown above, with a single item selected in Finder, it would be:

    theTarget="$(osascript -e "POSIX path of (application \"Finder\"'s selection as string)")"
    

    Or:

    theTarget="$(osascript -e "quoted form of POSIX path of (application \"Finder\"'s selection as string)")"