How to open a new Terminal tab in current working directory? I want to create and run a bash function that:


cd into a project's directory
Open a new tab in Terminal in the same directory
Open my dev tools and start dev services


Item #2 doesn't work as expected, the new tab doesn't change directory.

Here is the script (both functions residing in my .bashrc file:

# Open a new tab (needs a path as an argument)
new_terminal_tab(){
    osascript -e "tell application \"Terminal\"" \
                        -e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
                        -e "do script \"cd $1; clear;\" in front window" \
                        -e "end tell"
                        &gt; /dev/null
}

# Set up workspace
affiliatesForm(){
    # cd into the project's directory
    cd /Users/iamuser/Documents/path/to/project\ file
    # Get the working directory
    pwd=`pwd`

    # Open a new tab in Terminal and cd into project's directory
    # The idea is to have a tab with Rails server output, and another tab in the project's directory
    new_terminal_tab $pwd

    # Open the project in Sublime Text 2
    subl $pwd

    # Start the Rails server
    rails server
}


What am I doing wrong? What is this code doing that I don't know?



Update

The path for the directory I am trying to access has spaces in it. But escaping the space is not helping at all. The script works with paths that do not include spaces.
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" ] &amp;&amp; [ -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