6

I was trying to figure out how to make the current TTY session appear in the current Terminal window title bar by customising my .bashrc file, but I seem to be having a little trouble getting this to work.

I tried doing it like this;

PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h \w\a | $(tty | cut -d/ -f3,4)\]$PS1"

but that doesn't give the desired result when I do that. instead it goes like;

| pts/0user@hostname ~$

in the opening terminal screen instead of to title bar like so;

user@host ~ | pty/0

in my .bashrc file it looks like this

case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h \w\a | $(tty | cut -d/ -f3,4)\]$PS1"
    ;;
*)
    ;;
esac
  • -

Fixed with this.

PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h \w | $(tty | cut -d/ -f3,4)\a\]$PS1"

thanks to @Gilles for pointing that out in their post which made it little more clear what needed to be done.

6

To set the window title, emit the escape sequence \e]2;TITLE\a where \e and \a are the escape and bell character respectively. Since you're doing this inside the bash prompt, the escape sequence must be within \[…\] to tell bash that this doesn't produce any output inside the terminal.

You can use parameter expansion to truncate the /dev/ prefix, and call tty once and for all since it won't change.

TTY=$(tty)
PS1="\\[\\e[2;${TTY#/dev/}\\a\\]$PS1"
2
  • Where does the TTY variable come from? I don't seem to have it set on any of my systems (Debians, some CentOS, Bash on all of them, some under screen. zsh seems to set it, though). However, Bash (4.3) has the \l prompt escape for basename of the shell's terminal device name, but with device names like /dev/pts/14 it somewhat annoyingly shows only the number.
    – ilkkachu
    Aug 7 '16 at 14:16
  • @ilkkachu My bad, I made a mistake when I checked: indeed zsh sets it but bash doesn't. Aug 7 '16 at 18:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy