by foresto · 3y ago · 0 comments
The most common examples I see these days are for red/green/yellow status text in shell scripts. To anyone planning to do that, or even more complex stuff, please consider using tput instead.
tput setaf 1; echo this is red
tput setaf 2; echo this is green
tput setaf 3; echo this is yellow
tput setaf 8; echo this is dim
tput bold; echo this is bold
tput sgr0; echo this is normal
blue=$(tput setaf 4); normal=$(tput sgr0); echo ${blue}Color${normal} text.
(man terminfo for arcane details.)
It's wise to make sure output is going to a terminal before using colors, because they don't play well with logs or text processing commands. You can check with: test -t 1
If you use colors, please consider making them optional, since they don't work well for everyone or in every desktop color scheme. An environment variable makes a sensible switch.
Please don't do that without first checking the background colour. Yellow in particular on a light background is unreadable.
(On an xterm-compatible terminal you can get the current background colour with OSC 11 ; ? BEL. Some popular terminals lie about being xterm-compatible, though.)
¹ Ha, ha. The distro I use, Debian, also omits at least one POSIX standard utility by default, even though all of them used to fit nicely on systems with less disk than your current CPU's cache.
red=$(tput setaf 1 2>/dev/null || true)
echo ${red}text
And PC/3270. Some very powerful systems like Linux on IBM Z are POSIX and your default "interactive login" choice is PC/3270.
And in the long term, isn't this exactly the problem? Do we really want to perpetuate the status-quo of "I am in a somewhat POSIX environment, so the STDOUT/STDERR if interactive must behave exactly like xterm and if not I will just pretend it is xterm anyways and output garbage."?
Old glass terminals are still in use here and there, too.