The problem
In my daily work I usually deal with a large number of terminal windows or tabs; I feel it’s convenient to have a way to distinguish them one from the other at a glance, so I looked for a way to automatically change their background color when terminal starts.
Different terminals (e.g. Terminator vs XFCE4-Terminal vs…) support different color schemes and enable different options, but I finally found a bash-only-based solution, which works fine whatever terminal I use.
The solution
Bash supports changing background color through special output sequences: something like
1 | echo -ne "\e]11;#ff0000\a" |
can be for instance used to set background color to #ff0000
, #0000ff
, or #000000
.
So, everything I need is a way to
- choose a (background) color based on TTY id
- apply the chosen color to background through a command like those above
- do both thing every time a new bash is launched
The first problem can be solved through tty
command, which outputs something like
1 | $ tty |
So I can obtain tty number executing tty | tr -d [a-zA-Z/]
.
Given this tty number, I can select a color from an array, then use it to change background.
Adding to my path a script named change-background-color
and calling it in .bashrc
allows background color to be chosen automatically whenever I open an instance of bash.
Full code (with explanatory comments)
Bonus: my final implementation of the background color changing script allows two different usages:
- you can simply issue
change-background-color
, cyclically choosing the color from a finite set depending upon the tty number, or - you can provide a color symbolic name as parameter, using something like
change-background-color red
orchange-background-color olive
.
1 | // .bashcr |
Now the only question is to choose a set of not eye-offending colors… ;-)