Getting Finder (window | selection) paths inside Shell actions

For reference, a couple of macro fragments for use in Execute Shell Script actions:

FINDER paths from shell (window, selection).kmmacros (4.4 KB)

Getting the folder path of the front Finder window:

finderWinPATH=$(osascript -l JavaScript -e 'w=Application("Finder").windows();w.length?decodeURI(w[0].target().url().slice(7)):""');
echo $finderWinPATH

Getting the path of the first selected file in the front Finder window:

finderSelnPATH=$(osascript -l JavaScript -e 's=Application("Finder").selection();s.length?decodeURI(s[0].url().slice(7)):""');
echo $finderSelnPATH

(Note: Yosemite-only – uses Javascript for Applications)

2 Likes

and to get the paths of all files selected in the front Finder window (one path per line):

finderAllSelnPATHs=$(osascript -l JavaScript -e 'Application("Finder").selection().map(function(a){return decodeURI(a.url().slice(7))}).join("\n")');
echo $finderAllSelnPATHs

Finally, to capture the list of file paths in a Bash array, so that you can do something with them one by one, you can:

  1. set the Internal File Separator variable to linefeed with IFS='\n', and
  2. put brackets around the right hand side of the variable assignment expression.
IFS=$'\n';
finderSelnARRAY=($(osascript -l JavaScript -e 'Application("Finder").selection().map(function(a){return decodeURI(a.url().slice(7))}).join("\n")'));
for i in "${!finderSelnARRAY[@]}"
 do
	printf  "%s\t%s\n" "$i" "${finderSelnARRAY[$i]}"
done

Bash array of Finder selection paths.kmmacros (5.3 KB)

2 Likes

This is a great demonstration of JavaScript for Automation, which is incredibly powerful.

In this case, you can do them all in Keyboard Maestro, like this:

2 Likes