Pragmatism in the real world

Setting OS X's Terminal Tab to the current directory

I use many tabs in a Terminal window quite frequently, and while the window title will show the current directory name, the tab title doesn’t. You can manually change it using shift+cmd+i, but who can be bothered?

Automating it so that the tab title always matches the current directory turns out to be really easy and just requires a few lines in ~/.profile.

Firstly, we need a function that sets the tab’s title to the last segment of the current working directory:

function tab_title {
  echo -n -e "\033]0;${PWD##*/}\007"

We then just need to automate calling it whenever we change directory. The easiest way to do this is to change PROMPT_COMMAND:


That’s it. Whenever I change directory, or open a new terminal tab, then the tab’s title now matches the last segment of the directory for that tab. Much more useful!

Terminal tabs

8 thoughts on “Setting OS X's Terminal Tab to the current directory

  1. Rob, thanks for the tip, it's really useful. I think now I can start using terminal tabs in addition to displaying multiple windows across screen.

    However, it didn't work for me when I put this to .profile, but started working when I used .bash_profile.

  2. Igor,

    oneline is an alias. From my .gitconfig

        oneline = log --pretty=tformat:"%Cred%h%Creset%x09%Cgreen%an%Creset%x09%ad%x09%s"  --date=short --graph --decorate

    (not wrapped!)

  3. I recently switched to iterm. All the features are there and you can go at the beginning of the line using cmd+<-. (never worked on the regular terminal for some reason)
    Also you can split screen instead of having tabs.

  4. On a similar subject (well it's related to terminals, just not their title) I've used something like the following for many years to 'control' the length of my PS1 prompt (the bit next to the cursor which normally shows your path/host/username etc).

    In .bashrc :

    PS1="\$(hostname -s):\$(~/bin/prompt) \\$ "

    and ~/bin/prompt (needs to be executable) looks like :

    if [ ${#PWD} -gt $(($LENGTH)) ]; then
      echo "${PWD:0:$(($HALF-3))}...${PWD:$((${#PWD}-$HALF)):$HALF}" | \
        sed s/\\/home\\/$USER/~/
      echo "$PWD" | sed s/\\/home\\/$USER/~/

    So, now, if I'm in a deeply nested directly, my PS1 looks like :

    walnut:~/src/blahbl…dframework/zendframework1 $

    Instead of :


Comments are closed.