Get the Posix-Path(s) of the Finder-Selection

Hey Folks,

Anyone working with shell scripts often needs to grab a Posix path or three from item(s) in the Finder. Here's a simple macro to do just that.

Finder-Selection { Get Paths ~:… If Possible }.kmmacros (4.0 KB)

Example Result:

It's good practice to use home-directory-anchored paths when possible, because they are more likely to survive a change in hard-drive-name, user-name, or a move to a different computer.

Many years ago I predominantly used hard-coded-paths, and then I bought a new computer and named the user and hard drive differently... Nearly every script on my system that had a path-dependency broke, and I spent days fixing them. There were hundreds of them, and my work-flows were constantly interrupted until I finished the job.

I learned my lesson.


Now let's take on the task with AppleScript and add quoting:

set homeDir to text 1 thru -2 of (quoted form of (POSIX path of (path to home folder)))
set AppleScript's text item delimiters to homeDir
tell application "Finder" to set finderSelectionList to selection as alias list
if finderSelectionList ≠ {} then
  repeat with i in finderSelectionList
    set _temp to quoted form of (POSIX path of contents of i)
    if _temp starts with homeDir then set _temp to "~/'" & text item 2 of _temp
    set contents of i to _temp
  end repeat
  set AppleScript's text item delimiters to linefeed
  set the clipboard to (finderSelectionList as text)
else
  beep
  tell application "Finder" to display dialog "No Items are Selected in the Finder!" with title ¬
    "Error!" giving up after 10 with icon 0
end if

Outputs directly to the Clipboard.

Example:

~/'test_directory/example.html'
~/'test_directory/Excel Stuff/'
~/'test_directory/Excel'\''s Stuff/'

You'll note these are quoted with single-quotes. That form is necessary when the path has spaces, and the last path also escapes an existing single-quote in the folder name.

-Chris


Tags: @Finder, @Selection, @Finder-Selection, @Collection, @Text-Filter,


4 Likes