Skip to content

Instantly share code, notes, and snippets.

@pdanford
Last active November 14, 2024 21:13
Show Gist options
  • Save pdanford/158d74e2026f393e953ed43ff8168ec1 to your computer and use it in GitHub Desktop.
Save pdanford/158d74e2026f393e953ed43ff8168ec1 to your computer and use it in GitHub Desktop.
Launching iTerm2 from macOS Finder

Launching iTerm2 from macOS Finder

(Based on info from Peter Downs' gitub but with modified behavior to open a new terminal window for each invocation instead of reusing an already open window.)

The following three ways to launch an iTerm2 window from Finder have been tested on iTerm2 version 3+ running on macOS Mojave+.

pdanford - April 2020


To Launch an iTerm2 Window at:

a selected Folder in a focused Finder window - via keyboard shortcut

Starting sometime with iTerm2 version 3.x, it puts New iTerm2 Window Here in System Preferences -> Keyboard -> Shortcuts -> Services under the Files and Folders section. You just have to check it and Add Shortcut (e.g. ^T).

Note that sometimes macOS doesn't register a new keyboard Shortcut assignment immediately and may even require an OS restart to get it working. But also make sure the keyboard Shortcut is unique and not already assigned somewhere else.

This is only active when a Folder is currently selected in a Finder window that has focus.

the current working Folder of a focused Finder window - via keyboard shortcut

  1. Run Automator, File -> New and choose Quick Action.
  2. Click Library -> Utilities and double click Run AppleScript.
  3. Workflow receives Automatic (Nothing) in any application.
  4. Paste the script from AppleScript section below.
  5. Save; if Automator tries to save to iCloud drive, better to save locally - save as iTermOpenHereScript.workflow to the Desktop and then move it to ~/Library/Services.
  6. Add the keyboard shortcut under System Preferences -> Keyboard -> Shortcuts -> Services under the General section. Check iTermOpenHereScript and Add Shortcut (e.g. ^Y). Note that the first time you launch there may be a security popup saying iTermOpenHereScript wants access... Click OK to all.
  7. To prevent two windows from opening when you use the keyboard Shortcut when iTerm2 is not already running, set iTerm2's Preferences -> General -> Startup to Only Restore Hotkey Window for the Window restoration policy.
  8. To make windows open a bit faster, in iTerm2's Preferences -> General -> Closing uncheck Quit when all windows are closed.

Note that sometimes macOS doesn't register a new keyboard Shortcut assignment immediately and may even require an OS restart to get it working. But also make sure the keyboard Shortcut is unique and not already assigned somewhere else.

This is only active when a Finder window (or the Desktop itself) has focus (and ignores any selected Finder Folders).

The Desktop having focus isn't really the intended use case, but for completeness, if it's the Desktop that has focus the working directory of its last focused still-open Finder window is used. If the current Desktop does not have any Finder windows, it's a bit indeterministic, but a working directory from a Finder window in other Space is used. If there are no Finder windows open in any other Spaces, it will default to the user's home directory.

the current working Folder of a focused Finder window - via Finder Toolbar icon

To make an Automator App that can reside on the Finder Toolbar to open an iTerm2 window at the current focused working Folder:

  1. Run Automator, File -> New and choose Application.
  2. Click Library -> Utilities and double click Run AppleScript.
  3. Paste the script from AppleScript section below.
  4. Save; if Automator tries to save to iCloud drive, better to save locally - save as iTermOpenHereScript.app to the Desktop and then move it to ~/Library/Services.
  5. Drag and drop iTermOpenHereScript.app onto the Finder Toolbar while holding down the keys to place a toolbar launch icon. Note that the first time you launch there may be a security popup saying iTermOpenHereScript wants access... Click OK to all.
  6. Right click on the spot on the toolbar and select Icon Only. To replace the generic Automator app icon with the iTerm2 icon, i on the actual iTerm.app file in /Applications, select the application icon in the top left corner of the window and c. Then do i to iTermOpenHereScript.app file, select the application icon in the top left corner of the window and v.
  7. To prevent two windows from opening when you click the toolbar launch icon when iTerm2 is not already running, set iTerm2's Preferences -> General -> Startup to Only Restore Hotkey Window for the Window restoration policy.
  8. To make windows open a bit faster, in iTerm2's Preferences -> General -> Closing uncheck Quit when all windows are closed.

AppleScript

on run {input, parameters}
    set frontApp to (path to frontmost application as Unicode text)
    if (frontApp does not contain "Finder.app") then
        -- Finder does not have focus.
        return
    end if

    tell application "Finder"
        set listSize to count of (every window)
        if listSize is equal to 0 then
            -- The Finder desktop has focus and no windows anywhere else. default to home dir.
            set dir_path to "~"
        else
            try
                set dir_path to quoted form of (POSIX path of (Folder of the front window as alias))
            on error errMsg
                -- This is a special dir (e.g. Network or "machine name"). default to home dir.
                set dir_path to "~"
            end try
        end if
    end tell

    CD_to(dir_path)
end run

on CD_to(theDir)
    tell application "iTerm"
        activate -- Brings iTerm to the foreground
        set term_window to (create window with default profile)
        set sesh to (current session of term_window)
        tell sesh to write text "cd " & theDir & ";clear"
    end tell
end CD_to

📜 MIT License

@smile4yourself
Copy link

wonderful! thanks for sharing this!

@Horizonzhou
Copy link

Thank you, it's help a lot!

@Francesco146
Copy link

Francesco146 commented Nov 9, 2024

i suggest you add a activate in the CD_to function, in order to bring the window in the foreground.

proposed changes:

[...]
on CD_to(theDir)
    tell application "iTerm"
        activate -- Brings iTerm to the foreground
        set term_window to (create window with default profile)
        set sesh to (current session of term_window)
        tell sesh to write text "cd " & theDir & ";clear"
    end tell
end CD_to

I hadn't really noticed a new iterm windows not opening in the foreground because I always have iTerm itself running in the background already (even if no open terminal windows). So your addition is definitely a good idea for "cold" starts; added. Thanks!

-pdanford

@Setomidor
Copy link

Setomidor commented Nov 11, 2024

Super tiny suggestion, but add a space before "cd " to prevent it from showing in the history if HISTCONTROL is set to ignore spaces, i.e.:

[...]
tell sesh to write text " cd " & theDir & ";clear"
[...]

For me, I like seeing the cd <dir> in the history because if I need to I can tell were the subsequent terminal commands were executed (and in my case I also use export HISTCONTROL=ignorespace, but I still want the cd <dir> to show up in history).

But this is a good suggestion for those that want to modify their version depending on use case. Thanks!

-pdanford

Addendum: note iTerm's built-in New iTerm2 Window Here via macOS's System Preferences -> Keyboard -> Shortcuts -> Services under the Files and Folders section for opening a terminal at the selected Finder directory doesn't include any cd in the command history either. See a selected Folder in a focused Finder window - via keyboard shortcut section at top of gist.

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