Many terminal emulators allow to redefine colors with escape sequences, there's even a terminfo capability for that: initc
. With those, and assuming the terminfo database is correct, you can do:
tput initc 1 1000 0 0
To redefines color 1 (normally red
) to 1000‰ red, 0‰ green, 0‰ blue (#ff0000
).
So:
tput initc 1 1000 0 0
tput setaf 1 # to set the foreground color to 1
echo '██ = #FF0000'
tput sgr0
would do what you want.
To see what escape sequence that corresponds to:
$ tput initc 1 1000 0 0 | cat -vt
^[]4;1;rgb:FF/00/00^[\
So, on my terminal (xterm
), I can also do:
printf '\e]4;1;rgb:FF/00/00\e\\\e[31m██ = #FF0000\e[m\n'
Note that it changes the color of color1
. So if you change that to blue, all the text that had been displayed with that color will automatically change color.
To reset the colors to their initial values (initial at the time xterm
was started), with xterm
:
printf '\e]104\a'
Or to reset a single color:
printf '\e]104;1\a'
To query the current value of a color, there's a control sequence that causes xterm
to send back the value as terminal input. You can use the xtermcontrol
command to make it easier:
$ xtermcontrol --get-color1
rgb:ffff/ffff/0000
But that only works for the first 16 colors (xterm
nowadays supports 256).
On terminals that don't support resetting the colors to their defaults, but support 256 colors à la xterm
, you may want to use colors 17 and above as those are rarely used by applications.
However note that some terminfo database incorrectly specify how to assign and use those colors for those terminals, so you may want either to hardcode the escape sequences of force $TERM
to something like xterm-256color
.
printf '\e]4;17;rgb:ff/ff/00\a\e[38;5;17mThis is yellow\e[m\n'
printf '\e]4;18;rgb:ff/00/ff\a\e[38;5;18mThis is magenta\e[m\n'