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
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:
| Num | Color | Constant | RGB |
|---|---|---|---|
| 0 | black | COLOR_BLACK | 0,0,0 |
| 1 | red | COLOR_RED | 1,0,0 |
| 2 | green | COLOR_GREEN | 0,1,0 |
| 3 | yellow | COLOR_YELLOW | 1,1,0 |
| 4 | blue | COLOR_BLUE | 0,0,1 |
| 5 | magenta | COLOR_MAGENTA | 1,0,1 |
| 6 | cyan | COLOR_CYAN | 0,1,1 |
| 7 | white | COLOR_WHITE | 1,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