Skip to content

Instantly share code, notes, and snippets.

@monsieuroeuf
Last active November 4, 2022 01:42
Show Gist options
  • Save monsieuroeuf/df6eb11d7cabb4c8320cae92294646cc to your computer and use it in GitHub Desktop.
Save monsieuroeuf/df6eb11d7cabb4c8320cae92294646cc to your computer and use it in GitHub Desktop.
Quick little JXA (Javascript for Automation) for MacOS, just get the Finder selection and change it into paths. Suitable for a CLI workflow.
#!/usr/bin/osascript
// 2022-11-04
// returns target of front window if no actual selection
// prints the active Finder selection as POSIX paths,
// separated by newlines, ready to be eaten up by some other process
// I use in Fish shell like:
// for f in (finderselection.js) … etc
(() => {
function posixPath(url) {
return $.NSURL.alloc.initWithString(url).fileSystemRepresentation
}
const app = Application("Finder");
app.includeStandardAdditions = true;
let result = [];
const selection = app.selection();
if (selection.length > 0) {
selection.forEach((i) => {
let x = posixPath(i.url());
result.push(x)
});
} else {
// no selection? no worries
// return the target of the front finderwindow instead
result.push(posixPath(app.finderWindows[0].target().url()))
}
return result.join("\n")
})();
@monsieuroeuf
Copy link
Author

If using Fish shell, you could use it like this:

for f in (osascript ~/bin/finderselection.js )
 # do something here
end

… for example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment