Skip to content

Instantly share code, notes, and snippets.

@n8henrie
Last active August 10, 2023 17:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n8henrie/6cc2a43c141aea21e98c2fdfbb876090 to your computer and use it in GitHub Desktop.
Save n8henrie/6cc2a43c141aea21e98c2fdfbb876090 to your computer and use it in GitHub Desktop.
JXA to open a Terminal window to the frontmost Finder window
#!/usr/bin/osascript -l JavaScript
'use strict';
const DEBUG = false;
(function () {
const terminal = Application("Terminal")
// A few seconds to focus the appropriate Finder window
if (DEBUG) {
delay(2);
}
let windows = Application("Finder").finderWindows()
if (DEBUG) {
for (var window of windows) {
console.log("- " + window.target().url())
}
}
let url = windows.length > 0 ? windows[0].target().url() : "~"
if (DEBUG) {
console.log("url: " + url)
}
let path = decodeURIComponent(url).replace(/^file:\/\//, "")
if (DEBUG) {
console.log("path: " + path)
}
// https://stackoverflow.com/a/22827128
// Put path in single quotes, and escape internal single quotes
let quotedEscapedPath = `'${path.replace(/'/g, `'\\''`)}'`
let cmd = "cd " + quotedEscapedPath + "; clear;"
if (DEBUG) {
console.log("cmd: " + cmd)
}
// 20221112: For some reason seems to be necessary to now open a window first,
// then specify the window to run. I can't find a way to create a new window
// other than `doScript()` or `doScript("")`; `terminal.make({new: terminal.Window})`
// doesn't seem to work.
terminal.doScript()
terminal.doScript(cmd, {in: terminal.windows[0]})
terminal.activate()
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment