Skip to content

Instantly share code, notes, and snippets.

@eric-hu
Last active March 11, 2022 02:45
Show Gist options
  • Save eric-hu/5846890 to your computer and use it in GitHub Desktop.
Save eric-hu/5846890 to your computer and use it in GitHub Desktop.
Apple script to open an iterm2 tab from right-clicking on a file or folder in Finder. To use: (1) Open Automator (2) Create a new service (3) Change "Service receives selected" drop downs to "Files or folders" in "Finder" (4) Select "Run applescript" from the sidebar, then paste this script in and save
-- 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"
end tell
end tell
end tell
end CD_to
@kitizz
Copy link

kitizz commented Dec 17, 2016

I'm getting the same error as craigcosmo

@ttimasdf
Copy link

ttimasdf commented Dec 20, 2016

Here's my working fork, tested against latest iTerm2.

mainly changed:

  • detect file type by shell script, fix the problem in fork by @Leglaw that non-English (e.g. Chinese) locale may encounter.
  • create new tab if existing window is detected, instead of always creating new windows.

iTerm updated their interface. For those who keep getting error, have a try with it~ @craigcosmo @kitizz

@lrsantos11
Copy link

It's working for mw now @ttimasdf Thanks for the correction

@tokra
Copy link

tokra commented Mar 1, 2017

@ttimasdf not working for me, im getting this:
image

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