Thursday 28 September 2017

macos - Set the title of the terminal window to the current directory


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.



Answer



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.



No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...