For iTerm2, how do I make the working directory appear in the window title?

Solution 1:

With the \033]0;TEXT\007 escape sequence.

Example of use in Bash: echo -ne "\033]0;$PWD\007"

Which you could add to your $PROMPT_COMMAND if you use Bash, or otherwise attach to you PS1 so it gets re-evaluated often.

Example: export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'

Solution 2:

If you're using zsh (which is the default in macOS 10.15+), put this in your ~/.zshrc instead:

if [ $ITERM_SESSION_ID ]; then
precmd() {
  echo -ne "\033]0;${PWD##*/}\007"
}
fi

You can also spell \033 as \e and \007 as \a.

Solution 3:

Possibly a simpler answer is to use the string interpolation functionality offered by iTerm 2. Providing:

\(currentTab.currentSession.path)

in settings would result in a changed Window title. The option is accessible through Preferences>>Profiles>>[Profile we need to modify]>>Window

settings Settings

RESULTS Window title

Solution 4:

I like this answer from this gist to add it to the tab title

# put this in your .bash_profile
if [ $ITERM_SESSION_ID ]; then
  export PROMPT_COMMAND='echo -ne "\033];${PWD##*/}\007"; ':"$PROMPT_COMMAND";
fi

Solution 5:

You can relatively easily set the tab title in iTerm2 on macOS to the current working directory by placing the following in your ~/.zshrc profile:

# Set iTerm Tab Title to Current Working Directory
DISABLE_AUTO_TITLE="true"

iterm_tab_title() {
  echo -ne "\e]0;${PWD##*/}\a"
}
add-zsh-hook precmd iterm_tab_title

It uses a precmd hook function to execute before each prompt, setting the tab title by echoing out the current working directory.

For good measure, some Oh My Zsh themes mess around with the Terminal window title, so setting DISABLE_AUTO_TITLE="true" fixes this.