Change PS1 Color – How to Change PS1 Color When Connected via SSH

bashcolorsprompt

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?

Best Answer

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\] '