1

I am new to using Mac (Mac Pro, OS X 10.8.4) and I connect to many remote hosts using ssh. I have created aliases in .ssh/config file and would like to have the host alias as the name of the tab in terminal.

Can someone please advise on how it can be done?

Thanks much.

3

EDIT: On Yosemite (OS X 10.10) use this instead:

function ssh () 
{ 
     servername=$(echo $@ | sed -E 's|([- a-zA-Z0-9:/]+)( *[^@ ]*@)([^@ ]*)|\3|')
     echo -ne "\033]0;${servername}\007";
     /usr/bin/ssh $@
}

Note that the function expects username and server name to be specified as user@server (you can use the server IP address too: user@a.b.c.d, the tab name will be set to a.b.c.d). Other combinations like -l user server won't work properly.

You can unset the function with:

unset -f ssh

You can create a function named ssh that sets the terminal tab name and then invokes /usr/sbin/ssh:

function ssh () 
{ 
    servername=$(echo $@ | sed 's|\([- a-zA-Z0-9:/]\+\) *\([^-]\+@\)*\([-a-zA-Z0-9.]\+\)|\3|' | awk '{print $1}');
    echo -ne "\033]0;${servername}\007";
    /usr/bin/ssh $@
}
  • servername=$(echo $@ ...

    The first line extracts the server name from the arguments passed to ssh. I tested it against several possible ssh invocations with and without arguments but can't promise it's bullet proof.

  • echo -ne "\033]0;${servername}\007";

    The second line is where the magic happens. \033]0;<name>\007 is a ESCAPE sequence that sets the terminal tab name. See this Wikipedia article for more information - this particular escape code is listed in the non-CSI codes section.

  • /usr/bin/ssh $@

    Start /usr/bin/ssh with arguments provided.

Add the function to your ~/.bashrc file (if you don't use bash modify it to match your shell syntax and add it to your shell's startup file) so that it's always accessible.

Note that it will also set the terminal tab name when executing a remote command:

ssh user@server command

for example:

ssh jaume@myserver ls -l /
  • ssh -p 3422 user@host prints -p in tab title – Maxim Yefremov Mar 21 '15 at 6:07
  • 1
    @efr Please check my edited answer. – jaume Mar 21 '15 at 7:49
  • thank you ssh -p 3422 user@host now prints host – Maxim Yefremov Mar 21 '15 at 7:54
1

You can use the LocalCommand argument in your ~/.ssh/config file to run a bash or Applescript file that sets the tab name.

Bash Script: ~/.ssh/settabname.sh

#!/bin/bash

osascript -e 'delay 2' -e "tell application \"Terminal\" to tell window 1 to set custom title to \"$1\""

Your ~/.ssh/config file:

Host *
PermitLocalCommand yes

Host yourhostname
LocalCommand ~/.ssh/settabname.sh yourhostname &
...

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .