Change PS1 color when connected to other host via SSH

I’m trying to change PS1 look based on what host I’m connected in using SSH. My current PS1:

PS1='[e[1;32m]u@h[e[1;34m] w[e[1;31m]$(__git_ps1)[e[1;0;37m] $[e[0m] '

For host host1 I’d like to replace the first color with yellow which is 1;33 and for host2 take 1;35 as an example.

How can I figure out that I’m connected to the given host using SSH and alter PS1 accordingly?

Asked By: tomrozb

||

Construct your prompt specification in pieces, or use intermediate variables, or a combination of both. SSH sets the SSH_CLIENT variable, which indicates where you’re logged in from. You can then use the host name to determined where you’re logged into.

if [[ -n $SSH_CLIENT ]]; then
  case $HOSTNAME in
    *.example.com) prompt_user_host_color='1;35';; # magenta on example.com
    *) prompt_user_host_color='1;33';; # yellow elsewhere
  esac
else
  unset prompt_user_host_color # omitted on the local machine
fi
if [[ -n $prompt_user_host_color ]]; then
  PS1='[e['$prompt_user_host_color'm]u@h'
else
  PS1=
fi
PS1+='[e[1;34m] w[e[1;31m]$(__git_ps1)[e[1;0;37m] $[e[0m] '

Like the other one, but you could also use the separate rc file for ssh.

<<SSH_RC 
    tee -a ~/.ssh/rc
case $HOSTNAME in
    (host1) sshclr=1;;
    (host2) sshclr=3;;
esac

…and wherever you are assigning your $PS1

PS1="[e[1;$((32+ssh_clr))"'...

…you could leave it in single quotes, too…

PS1='[e[$((!$?|4));$((32+sshclr))...'

…which should underline if the last command executed exited with a non-zero exit code. Here’s a picture…

enter image description here

I added the ${SSH_CLIENT+ssh:} expansion there to clearly denote @ssh: when connected that way…

Answered By: mikeserv
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.