SSH within SSH displays the wrong machine name in the xterm title bar

sshwindow titlexterm

I am working on a distributed system connecting to several servers at once. Nothing is started manually in the program I am working on, but this is how to recreate the error manually.

I start a xterm then I SSH to a machine like this:

ssh machine_1

In there I start another xterm in the first xterm like this:

xterm &

Then the title bar of the new xterm window is something like "username (on machine_1)"

In this xterm I SSH to another machine like this:

ssh machine_2

But then the title bar remains like this: "username (on machine_1)"

even though I am logged on to machine_2. I want it to say "username (on machine_2)". Completely removing the parenthesis would also be fine.

I tried xtermset but that does not affect the parenthesis.

Best Answer

Either xterm or the shell on machine_1 is configured to set the terminal title to contain the machine name. Configure your shell on machine_2 to set the terminal title to contain the machine name. You'll also want to make sure that the shell on machine_1 resets the title when the ssh session is terminated. The usual way to do this is to make the shell reset the terminal title whenever it displays a prompt. This has the added benefit of resetting the terminal title to something sensible if a full-screen text mode application sets it while it's running.

You can set the title of an xterm by displaying the escape sequence \e]2;my title here\a where \e is an escape character (\033) and \a is a bell character (\007). Include this sequence in your shell prompt. For bash, put a line like this in your ~/.bashrc:

PS1="\[\033]2;xterm on $HOSTNAME\a\]$PS1";;

The backslash-bracket punctuation \[…\] tell bash that what is inside has a width of 0 (if you leave off the brackets, the display will be garbled).

For more a fancy title that changes after each command, you can include variable and command substitutions in the prompt string if you set the promptvars option.

In zsh, set the title from the precmd function, which is executed before each prompt.

precmd () {
  print -n "\e]2;xterm on $HOSTNAME in $PWD\a"
}

While you're at it, you can set the title from preexec to contain the name of the running command. Here's a simple way which doesn't react very well to unprintable characters in the command:

preexec () {
  print -nr $'\e]2;'"xterm on $HOSTNAME running $2"$'\a'
}
Related Question