How to open a new Terminal tab in current working directory?

Opening a new tab in Terminal should by default retain the current directory. If it doesn't, you may've broken the $PROMPT_COMMAND.

Also remember to not replace the previous value if you intend to add custom behaviour by adding ; $PROMPT_COMMAND at the end.

PROMPT_COMMAND="my_custom_function; $PROMPT_COMMAND"

For reference, here's the default from /etc/bashrc (OS X 10.9):

# Tell the terminal about the working directory at each prompt.
if [ "$TERM_PROGRAM" == "Apple_Terminal" ] && [ -z "$INSIDE_EMACS" ]; then
    update_terminal_cwd() {
        # Identify the directory using a "file:" scheme URL,
        # including the host name to disambiguate local vs.
        # remote connections. Percent-escape spaces.
        local SEARCH=' '
        local REPLACE='%20'
        local PWD_URL="file://$HOSTNAME${PWD//$SEARCH/$REPLACE}"
        printf '\e]7;%s\a' "$PWD_URL"
    }
    PROMPT_COMMAND="update_terminal_cwd; $PROMPT_COMMAND"
fi

I know this question is a little dated but I just found an answer that would be useful for iTerm2 users on Mac OS X.

Under the "profile tab" in iTerm2 preferences you can set exactly where iterm opens up new tabs under the "Working Directory" heading

iterm preferences

After that, close and restart iTerm and you should be good to go!


So as it was mentioned, my script worked with paths that didn't include spaces. It turns out that the solutions lies in wrapping the variable (inside new_terminal_tab()) in single quotes like so:

-e "do script \"cd '$1'; clear;\" in front window" \

Amazing what quotes can do isn't it?