tput setaf 1; hostname; tput sgr0
tput
queries the terminal database for the corresponding capability. Here setaf
for set ANSI colour 1 (red), sgr0
to select graphic rendition none to go back to default attributes. Instead of tput sgr0
, you can also use tput op
(original pair) to only reset background and foreground colour and leave other graphic attributes (bold, underline, standout, reverse...) alone.
Some shells like zsh
, tcsh
or fish
have builtin support to query that database or map color names to ANSI codes (like zsh
or fish
), but not bash
.
In zsh
, using prompt expansion to print the hostname in red
:
print -P '%F{red}%m%f'
(%f
only resets the foreground colour)
In tcsh
or zsh
with the echotc
builtin using termcap codes instead of terminfo:
echotc AF 1; hostname; echotc me
(zsh
has echoti
for the terminfo codes setab/sgr0 like modern versions of tput
).
In zsh
, the %
parameter expansion flag turns on prompt expansion upon parameter expansion, so you can do:
red=%F{red} normal=%f
echo ${(%)red}whatever%{(%)normal}
In zsh
, you'll also find a colors
autoloadable function that you can run to have helpers to write things in colour:
autoload colors; colors
echo $fg[red]whatever$fg[default]
hostname
should always output red? – Sparhawk May 05 '17 at 00:11command the-original-command "$@"
, then the end-color sequence. You might be able to make a set-color function that creates such functions on-demand as well. Beware commands (such as some greps) that may declare their own colors. – Jeff Schaller May 05 '17 at 02:45