coderrr

January 30, 2010

How to create a shortcut key to open a new terminal window in the current working directory on OSX

Filed under: osx — Tags: — coderrr @ 2:04 pm

Shameless Plug: Use a Mac OS X Compatible VPN Service to protect your privacy on the Internet.

In gnome-terminal I always used ctrl-shift-n to open a new terminal window in the current working directory (cwd). Having been forced to switch to OSX I was totally missing this functionality in the Terminal app. I often spawn a new terminal to quickly execute a quick command or series of commands and then close it. Not finding any satisfactory solutions online I hacked one together which works.

My Solution

First make sure the following checkbox is enabled: Terminal -> Preferences -> Window ->TTY Name

Now edit your ~/.bash_profile and add this line:

export PROMPT_COMMAND='pwd > /tmp/cwd.`ps -o tty= -p $$`'

Next create an applescript with the following content (if you don’t know how to create/compile an applescript just use the AppleScript Editor) and save it in your Scripts directory:

tell application "Terminal"
	set ttyname to (tty of (front window))
	set AppleScript's text item delimiters to "/"
	set cwd to do shell script "cat /tmp/cwd." & (item 3 of (text items of ttyname))
	activate
	do script "cd '" & cwd & "'"
end tell

Now that you have saved the script we only need to bind a key to it. This requires an extra application as I don’t know of any stock way to do this in OSX. I use FastScripts to do this. I believe KeyboardMaestro also has this capability, as I’m sure lots of other apps I don’t know about do. Feel free to leave a comment with suggestions on better/free-er ones.

With FastScripts you just drop down the menubar which should already contain your script if you saved it in your Scripts directory. Find the script and cmd-click it, this will bring up a popup which allows you to assign a global shortcut.

How it works

The $PROMPT_COMMAND is executed before each prompt (i.e. after any directory change). pwd > /tmp/cwd.`ps -o tty= -p $$` writes out the current working directory to a temp file containing the name of the current TTY. So for each Terminal session there will be a corresponding file which is kept up to date with its current directory. The applescript grabs the TTY from the current active Terminal and reads its cwd file to find the current directory. It then spawns a new terminal window and tells it to cd to that directory.

* note: if you are in a screen this will not work because the TTY will be different than the one in the Terminal’s window.

Let me know if you have a better solution, I’m sure there’s one out there.

Customized Silver is the New Black Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 28 other followers