← TUTORIAL
#bash

Bash - Colored text output with tput

tput generates terminal control sequences for color, bold, underline, and other text formatting. Use it in bash scripts to make output readable at a glance.

Usage

tput queries the terminfo database and emits the appropriate escape sequences for the current terminal:

tput, reset  -  initialize a terminal or query terminfo database

Wrap text between a tput formatting call and a reset to return to default styling:

tput setaf 1; echo "Here is red text"; tput sgr0

Use ; rather than && so that if tput fails, the text still prints.

Shell variables

Store format codes in variables to avoid repeating the tput calls and to keep the code readable:

green=`tput setaf 2`
blue=`tput setaf 4`
reset=`tput sgr0`
echo "${green}green text ${blue}blue text${reset}"

tput produces character sequences the terminal interprets as formatting instructions. The sequences do not appear as visible text but they can be saved to files or piped to other programs.

Command substitution

Skærmbillede 2015-03-29 21.21.14 Example from Debian

echo "$(tput setaf 1)Color text $(tput setab 3)and custom background$(tput sgr0)"

This one-liner prints text in red with a yellow background.

Colors in Foreground and background

Two commands control color:

tput setab [1-7]   # sets the background color
tput setaf [1-7]   # sets the foreground color

Color values:

NumColorConstantRGB
0blackCOLOR_BLACK0,0,0
1redCOLOR_RED1,0,0
2greenCOLOR_GREEN0,1,0
3yellowCOLOR_YELLOW1,1,0
4blueCOLOR_BLUE0,0,1
5magentaCOLOR_MAGENTA1,0,1
6cyanCOLOR_CYAN0,1,1
7whiteCOLOR_WHITE1,1,1

Text mode commands

tput bold   # select bold mode
tput dim    # select dim (half-bright) mode
tput smul   # enable underline mode
tput rmul   # disable underline mode
tput rev    # turn on reverse video mode
tput smso   # enter standout (bold) mode
tput rmso   # exit standout mode

tput accepts scripts with one command per line. Avoid temporary files by echoing a multiline string and piping it:

echo -e "setf 7\nsetb 1" | tput -S   # set fg white and bg red

See also: LinuxCommand.org