Open a new tab in the same directory

Use Oh-My-Zsh and add the 'osx' plugin in your ~/.zshrc like:

plugins=(osx)

If you use OSX's Terminal App, you also need to add the terminalapp plugin too: credit

plugins=(osx terminalapp)

If you use iTerm you need to set a configuration option (Note that you may not need the zsh plugins for this to work): credit

Preferences > Profiles > Default > General > Working Directory > Reuse previous session's directory option

iTerm2 Preferences panel update to reuse previous session directory.

That's all you need to do!


Another option now available in Mac OS X Lion is using the built-in feature. It uses 'escape sequences' to find out the current directory. For me it works if I use these commands in my .zshrc:

precmd () {print -Pn "\e]2; %~/ \a"}
preexec () {print -Pn "\e]2; %~/ \a"}

it is also possible to use PS1 (for Bash, from this wiki):

export PS1="\[\e]2;\u@\H \w\a\e[32;1m\]>\[\e[0m\] "

where \e]2; is the escape sequence to print things in the titlebar. It seems that Terminal.app is getting its information from there.

More information:

  • http://networking.ringofsaturn.com/Unix/Bash-prompts.php
  • http://www.funtoo.org/wiki/Prompt_Magic
  • http://tldp.org/HOWTO/Bash-Prompt-HOWTO/xterm-title-bar-manipulations.html

This is a very simple version which I used in bash and also works in zsh. It saves the current folder in a file, after every command (Doesn't hurt too much IMO) and opens a new terminal in the saved current folder.

add the following to .zshrc

# emulate bash PROMPT_COMMAND (only for zsh)
precmd() { eval "$PROMPT_COMMAND" }
# open new terminal in same dir
PROMPT_COMMAND='pwd > "${HOME}/.cwd"'
[[ -f "${HOME}/.cwd" ]] && cd "$(< ${HOME}/.cwd)"