Bash – Display current TTY/PTY in Terminal title

bashpromptwindow title

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.

Best Answer

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"
Related Question