Set the title of the terminal window to the current directory

45,375

Solution 1

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.

Solution 2

Copy & paste into file ~/.profile:
PROMPT_COMMAND="echo -ne \"\033]0;${PWD##*/}\007\"; $PROMPT_COMMAND"

This will set the title of the current terminal tab to the name of the folder you are in (NOT the whole path).
So...
Developer/Applications/Utilities/Bluetooth/ becomes => Bluetooth

Solution 3

As of Mac OS X Lion 10.7, Terminal has an explicit escape sequence for setting the working directory, which Terminal displays using the standard window "proxy" icon. This enables you to Command-Click it to see the path, reveal in Finder, or drag it like any other folder. In addition, Terminal can use this to create another terminal at the same directory, and to restore the working directory when quitting/restarting Terminal (when Resume is enabled). It also enables restoring directories for Window Groups.

It's the same Operating System Command (OSC) escape sequence as for the window and tab titles, but with the first parameter set to 7. The value should be a "file:" URL, which enables percent-encoding special characters so it can handle all valid pathnames. You should also include the hostname so Terminal can determine whether it's a local directory; Terminal will avoid using it as the current working directory if it's from a different host.

On a related note, Terminal similarly supports setting the "represented file" using the OSC escape sequence with a parameter of 6. If set, the proxy icon will display this instead of the working directory. For example, I have emacs and less configured to reflect the currently displayed file/buffer in the proxy icon. This enables these tty-based programs to be more integrated with the surrounding OS.

The working directory behaviors are enabled by default for bash (the default shell on Mac OS X). See /etc/bashrc for the relevant code.

It's also probably worth mentioning that Lion Terminal now supports setting the tab title independently from the window title using the OSC escape sequence.

Solution 4

Apart from recommending you use the Apple Terminal specific Operating System Command escape sequence: ESC ] Ps ; Pt BEL where Ps is 7 and Pt is a file: URL; it's worth adding that in Mac OS X 10.11 (and probably since 10.7) there's a file /etc/bashrc_Apple_Terminal (uneditable under 10.11) which defines the convenient update_terminal_cwd() as (without the comments):

update_terminal_cwd () 
{ 
    local url_path='';
    { 
        local i ch hexch LC_CTYPE=C LC_ALL=;
        for ((i = 0; i < ${#PWD}; ++i))
        do
            ch="${PWD:i:1}";
            if [[ "$ch" =~ [/._~A-Za-z0-9-] ]]; then
                url_path+="$ch";
            else
                printf -v hexch "%02X" "'$ch";
                url_path+="%${hexch: -2:2}";
            fi;
        done
    };
    printf '\e]7;%s\a' "file://$HOSTNAME$url_path"
}

You could use this on your remote boxes too, in case you were thinking of doing so and then scratching your head on correctly encoding the file URL in bash.

And if you change PROMPT_COMMAND in your own .bash_profile or .bashrc you might forget to call this. In the same file they show an example of chaining it a bit better with:

PROMPT_COMMAND="update_terminal_cwd${PROMPT_COMMAND:+; $PROMPT_COMMAND}"

Personally in my .bash_profile I wanted to add the git prompt so I did this:

local git_path=/Applications/Xcode.app/Contents/Developer/usr/share/git-core
for f in $git_path/git-completion.bash $git_path/git-prompt.sh
do
  if [[ -f "$f" ]]; then
    . "$f"
  fi
done
get_sha() {
    git rev-parse --short HEAD 2>/dev/null
}
if [ "function" = $(type -t __git_ps1) ]; then
    export GIT_PS1_SHOWDIRTYSTATE=1
    GIT_PS1_SHOWSTASHSTATE=1
    GIT_PS1_SHOWUNTRACKEDFILES=1
    GIT_PS1_SHOWCOLORHINTS=1
    GIT_PS1_DESCRIBE_STYLE="branch"
    GIT_PS1_SHOWUPSTREAM="auto git"
    export PROMPT_COMMAND="$PROMPT_COMMAND${PROMPT_COMMAND:+; }"'__git_ps1 "\[\e[0;32m\]\u\[\e[1;32m\]@\h\[\e[0m\]:\[\e[0;34m\]\w\[\e[0m\]" "\$ " "\n{%s $(get_sha)}"'
fi

Solution 5

Assuming you are using the default MAC Terminal, you can use the following one in .profile since "set_prompt" by itself may send you to the root folder when you open a new tab:

set_prompt () {
    BASE_PATH="${PWD##*/}"
    echo -ne "\033]0;$BASE_PATH\007"
}
set_my_tab () {
   update_terminal_cwd
   set_prompt
}

PROMPT_COMMAND=set_my_tab
Share:
45,375

Related videos on Youtube

ConquestXD
Author by

ConquestXD

Hi, I am Kåre Morstøl (a.k.a. Kare Morstol or kareman), a freelance software developer living in Ålesund, Norway. I specialise in iOS and Mac frameworks. Mac commandline applications and shell scripting. Mac automation. All of it in Swift. My current public projects are SwiftShell, a Swift framework for shell scripting, and FootlessParser, a parser combinator written in Swift.

Updated on September 17, 2022

Comments

  • ConquestXD
    ConquestXD over 1 year

    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.

    • cregox
      cregox about 14 years
      I always wonder why not even people who answer the question remember to vote it up.
  • ConquestXD
    ConquestXD over 14 years
    Should have mentioned I am using bash, I have updated the question.
  • Darren Hall
    Darren Hall over 14 years
    Added the bash method from the listed link.
  • ConquestXD
    ConquestXD over 14 years
    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 \$ ".
  • cregox
    cregox about 14 years
    To me the example ( PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"' ) only worked if set on ~/.profile.
  • Chris Page
    Chris Page over 12 years
    "If we want to use the '~' shorthand we need to embed the escape string in the prompt" You can use the following to replace the full home directory pathname with tilde: ${PWD/#${HOME}/\~}
  • Chris Page
    Chris Page over 12 years
    "The first line contains two special characters that can't be copied/pasted" Instead of using echo use printf, which lets you express those characters (ESC and BEL/Control-G) with escape sequences: printf '\e]0;$@\a"
  • Chris Page
    Chris Page over 12 years
    As of Mac OS X Lion 10.7, Terminal has an explicit escape sequence for setting the working directory. It uses a URL, so you can use percent-encoding for special characters and support all valid pathnames. See my answer to this question for details.
  • Tom
    Tom about 10 years
    On mavericks the file to edit is ~/.bash_profile
  • Assembler
    Assembler over 9 years
    The update_terminal_cwd function will set the proxy icon to the current working directory. By default $PROMPT_COMMAND is update_terminal_cwd.
  • Chris Page
    Chris Page over 9 years
    @jtbandes That’s what I was referring to when I wrote “The working directory behaviors are enabled by default for bash…”.
  • Assembler
    Assembler over 9 years
    Yep. I just discovered how it works and thought it might be useful for future googlers!
  • coredumperror
    coredumperror almost 9 years
    @MattTagg Sure, you just need to put it into your ~/.profile (or equivalent) file on the remote machine.
  • Madhur Kerni
    Madhur Kerni about 4 years
    Chris, how much of this is still relevant with Catalina and the default zsh?
  • Madhur Kerni
    Madhur Kerni about 4 years
    Thanks, you’ve updated the main point in superuser.com/a/328148/74409, though I’m still intrigued by your opening paragraph.
  • christopher.online
    christopher.online about 3 years
    the link seems to be dead
  • Blundering Philosopher
    Blundering Philosopher about 3 years
    For some reason, the ending $PROMPT_COMMAND seemed to be doing weird things for me, so I just used export PROMPT_COMMAND='echo -ne "\033]0;${PWD##*/}\007"' (on macOS Big Sur)