There are many “Open Terminal Here”, “New Terminal Here” or “Open Terminal at Finder Window” scripts floating around, also on this forum (1, 2, 3, …).
But none of them does exactly what I want, so here’s another script/macro:
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
# Preferred app
set myTerminal to "com.apple.Terminal"
-- set myTerminal to "com.googlecode.iterm2"
# Items that should be treated as folders
# Examples: "Application", "Bundle", "Rich Text Document with Attachments", …
set folderLike to {"Folder"}
tell application "Finder"
try
try
set targetDir to the selection
set targetDir to item -1 of targetDir as alias
if kind of targetDir is not in folderLike then
set targetDir to parent of targetDir as alias
end if
on error
set targetDir to target of Finder window 1 as alias
end try
on error
set targetDir to path to home folder as alias
end try
end tell
do shell script "open -b" & space & myTerminal & space & quoted form of (POSIX path of targetDir)
New Terminal Here.kmmacros (2.6 KB)
How it works
“Selected” means ‘selected in the frontmost Finder window’.
- A folder is selected: open new Terminal window at the folder
- A non-folder file is selected: open new Terminal window at the containing folder
- Nothing is selected: open new Terminal window at the frontmost Finder window’s folder
- Nothing is selected and frontmost Finder window is unsuitable (e.g. “Recents” or Spotlight Search): open new Terminal window at $HOME
- No Finder window: open new Terminal window at $HOME
Note: The behavior as outlined above is exactly what I personally expect from my Terminal script. If your expectations are different, I recommend to first try one of the other scripts available (see links above).
Usage
- Download and install the macro.
- Make sure the macro and its containing group are activated.
- Assign a trigger, preferably a hotkey.
- Open a Finder window and optionally select an item.
- Run the macro.
Notes
- If you prefer iTerm instead of Terminal, then comment/uncomment the corresponding lines in the script (
set myTerminal to […]
). -
Packages (bundles) are treated as non-folder files. This is intended. (This can be changed by adding kinds to the
folderLike
list, for example"Application"
.) - The script works perfectly fine also with LaunchBar (that’s how I use it). Just remember to add a pro-forma
open
handler, otherwise the action will fail if you accidentally send the Finder selection to LB. - In case of multiple selections, always the last selected item will be used.
- iTerm by default opens a new tab instead of a new window. You can rectify the behavior in iTerm’s preferences > Advanced > Windows.
- I’m using the script for quite some time, but before posting it here I made some minor modifications (e.g. the config options). So, it is possible that I also introduced a bug. Let me know if you run into any issues.