Open iTerm Tab from Finder by Shortcut

Feb 4, 2016 · 2 minute read · Comments
#Terminal

To open the currently selected Finder folder in a new iTerm tab:

  1. Create a new service in Automator.
  2. Select “Service receives no input” in “Finder”.
  3. Add the Action “Get Selected Finder Items” from the available Actions in the library on the left.
  4. Add the “Run AppleScript” from available actions and add after the previous action.
  5. Paste the following Apple Script:

    -- Adapted from these sources:
    -- http://peterdowns.com/posts/open-iterm-finder-service.html
    -- https://gist.github.com/cowboy/905546
    -- 
    -- Modified to work with files as well, cd-ing to their container folder
    on run {input, parameters}
      tell application "Finder"
            set my_file to first item of input
            set filetype to (kind of (info for my_file))
            -- Treats OS X applications as files.  To treat them as folders, integrate this SO answer:
            -- http://stackoverflow.com/a/6881524/640517
            if filetype is "Folder" or filetype is "Volume" then
                set dir_path to quoted form of (POSIX path of my_file)
            else
                set dir_path to quoted form of (POSIX path of (container of my_file as string))
            end if
        end tell
        CD_to(dir_path)
    end run
    
    on CD_to(theDir)
        tell application "iTerm"
            activate
            try
                set t to the last terminal
            on error
                set t to (make new terminal)
            end try
            tell t
                launch session "Default Session"
                tell the last session
                    write text "cd " & theDir
                    write text "ls -ls"
                end tell
            end tell
        end tell
    end CD_to
    
  6. Save the script and go to the keyboard shortcuts tab in system preferences. The script should appear in Services > General. Add any shortcut to it. Done.

Original source : https://gist.github.com/eric-hu/5846890

comments powered by Disqus