Bash – How to set up `screen` to modify the window title and xterm-window title

bashgnu-screenpromptxterm

I'd like to have my current $PS1 prompt (\u@\h:\w$(__git_ps1 "(%s)")\$ plus some coloring) to be also used as screen's window title (in the hardline) and as the xterm window title. How can this be achieved?

Best Answer

An incomplete solution would be to modify your $PS1 prompt once inside a GNU screen. Start by modifying your shell's RC file (ie ~/.bashrc). Look for a case statement that evaluates $TERM:

case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

Add the following prior to the catch all (ie *)):

screen)
    PS1='\e]0;\u@\h:\w\a\ek\u@\h:\w\e\\\u@\h:\w$(__git_ps1 "(%s)")\$ '
    ;;

This will modify your hardstatus: \e]0;...\a

This will modify your window title: \ek...\e\\

The hardstatus will not show up unless you have configured it to do so. For example, you could add the following to your .screenrc:

hardstatus alwayslastline

Complex hardstatus string options will continue to work. You can substitute your now dynamic stored hardstatus for the current window using %h:

hardstatus string '%{= kw}[ %h ] %=%{w}[ %{r}%l%{w} ]%{w}[%{y} %Y-%m-%d %C %A %{w}]%{w}'

This will set the hardstatus line to the stored hardstatus between two brackets on the left side of the screen and the CPU utilization to the right along with the date and time.

Example:

 [ username@host:~ ]                    [ 0.00 0.01 0.00 ][ 2012-11-27  4:13 PM ]

CAVEATS

  1. This will most likely break your cursor offset in your shell's history recall. (Hit your up arrow a few times, then try to edit that line. You'll see what I mean.) This is because most shells use the length for $PS1, and this will include the non-printable characters added to $PS1.

  2. This will most likely break the xterm title bar, "freezing" it to the last status set prior to running GNU screen. What is interesting is that applications like vim that update the title bar will continue to work.

  3. Manually setting the screen title (ie C-A A) will still work until the command prompt is updated.

Related Question