Is it possible to automatically change the color of the terminal based on which server I am connected to through SSH?

For instance, when I fire up the terminal it has the standard colors defined under my profile. Then I ssh to ssh.example.com and the color changes to black & green instead. Then I exit the session and the color returns to the standard color theme.

I know that you could do this manually. But I'm looking for an automated way.

2 Answers 2


Yes, you can by changing the PS1 value in .bashrc file on every hostname where you are connecting with ssh.

See this answer to view how to costumize as you like the bash changing the PS1 value.

ssh colored

On my machine (radu@Radu) I have in .bashrc:

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;35m\]\u@\h\[\033[00m\]:\[\033[01;34m\] \w\[\033[01;37m\] > '

On the hosted machine (radu@ubuntu) I have:

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;35;40m\]\u@ubuntu\[\033[00;40m\]:\[\033[01;34;40m\] \w\[\033[01;32;40m\] > '
  • 8
    How exactly did u manage to change the background color?
    – chrisg86
    Mar 11, 2015 at 13:31
  • The '3x' codes change the foreground color. the '4x' codes change the background color. Notice that the hosted machine has '4x' codes, but the local does not. arwin.net/tech/bash.php
    – FlipMcF
    Sep 8, 2016 at 16:35
  • Is there a way to get the same result without changing anything on the remote box? We use VMs, and changes wouldn't be persisted for long...
    – Christian
    Jul 31, 2017 at 11:08

If you are using xterm, this works great: https://github.com/fboender/sshbg

How does it work?

Black unix magic. Well, not really. Well, kinda...

SSH lets you run a local command before the connection to the remote host is established. Some terminals allow you to set the background color with an escape sequence. It's possible to detect if the SSH command has exited from the locally executed command by polling the parent process PID in the background. Combine the three and presto! Background colors.

sshbg matches (regex) entries in a configuration file against the provided hostname. That results in a profile name, which has a background color associated with it. See the "Config file" section at the bottom of this page for more info.

Installation and usage


  • Python v3.x+
  • A supported terminal

Clone this repo:

git clone [email protected]:fboender/sshbg.git
cd sshbg

Copy the sshbg script to some dir in your PATH, for example:

sudo cp sshbg /usr/local/bin/

Copy the sshbg.conf file to ~/.config/sshbg.conf:

cp sshbg.conf ~/.config/

Enable the LocalCommand configuration setting in your SSH config. You can do this on a host-by-host basis, or with wildcards. To enable it for all hosts, make your SSH config look like this:

$ cat ~/.ssh/config
PermitLocalCommand yes
Host *
    LocalCommand sshbg "%n"

You must log in to answer this question.

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