vote up 0 vote down star
1

How can I get the Terminal.app in OS X to display the current directory in its window or tab title?

I'm using the bash shell.

flag

2 Answers

vote up 3 vote down check

Depends on your shell.

This article displays multiple methods.

I personally use zsh which has a convenient precmd() function which is run before each prompt.

    precmd () { print -Pn "\e]2;%n@%M | %~\a" } # title bar prompt

Although the other questions list bash methods, they alias cd. Bash provides an inherent method that chains off just the prompt.

bash

bash supplies a variable PROMPT_COMMAND which contains a command to execute before the prompt. This example (inserted in ~/.bashrc) sets the title to "username@hostname: directory":

 PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'

where \033 is the character code for ESC, and \007 for BEL. Note that the quoting is important here: variables are expanded in "...", and not expanded in '...'. So PROMPT_COMMAND is set to an unexpanded value, but the variables inside "..." are expanded when PROMPT_COMMAND is used.

However, PWD produces the full directory path. If we want to use the '~' shorthand we need to embed the escape string in the prompt, which allows us to take advantage of the following prompt expansions provided by the shell:

\u          expands to $USERNAME
\h          expands to hostname up to first '.'
\w          expands to directory, replacing $HOME with '~'
\[...\]     embeds a sequence of non-printing characters

Thus, the following produces a prompt of "bash$ ", and an xterm title of "username@hostname: directory" ...

 case $TERM in
     xterm*)
        PS1="\[\033]0;\u@\h: \w\007\]bash\$ "
        ;;
     *)
        PS1="bash\$ "
        ;;
 esac

Note the use of [...], which tells bash to ignore the non-printing control characters when calculating the width of the prompt. Otherwise line editing commands get confused while placing the cursor.

link|flag
Should have mentioned I am using bash, I have updated the question. – Kare Morstol Dec 7 at 19:13
Added the bash method from the listed link. – Darren Hall Dec 7 at 19:17
Very good. To get only the path to the current directory in the title and the name of the current directory in the prompt I just used PS1="\[\033]0;\w\007\]\W \$ ". – Kare Morstol Dec 7 at 19:42
vote up -1 vote down

Enter this into your ~/.profile or equivalent file:

function settitle() { echo -n "]0;$@"; }
function cd() { command cd "$@"; settitle `pwd -P`; }

export PS1='\W \$ '

settitle `pwd`

The first line contains two special characters that can't be copied/pasted, but you can download the text from here: http://blog.nottoobadsoftware.com/files/setterminaltitle.sh.

link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.