Color output lets a Bash script make warnings, success messages, and errors stand apart in a terminal. It works best when the script is writing to an interactive terminal that understands ANSI Select Graphic Rendition sequences, because redirected logs and plain text files may store the escape characters instead of showing colors.
Bash can store terminal control bytes with ANSI-C quoted strings such as $'\033[31m', then print them with printf "%s...%s" around visible text. That keeps escape handling in the variable assignment instead of asking printf to reinterpret every message string.
The sample script enables red, green, and yellow labels only when standard output is an interactive terminal and NO_COLOR is unset. Redirected output and one-off NO_COLOR runs fall back to plain text, and the reset string after each label keeps later output at terminal defaults.
Related: How to create and run a Bash script
Related: How to use variables in Bash scripts
Related: How to use conditionals in Bash scripts
#!/usr/bin/env bash set -euo pipefail if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then red=$'\033[31m' green=$'\033[32m' yellow=$'\033[33m' reset=$'\033[0m' else red="" green="" yellow="" reset="" fi printf "%sERROR%s disk space low\n" "$red" "$reset" printf "%sOK%s backup completed\n" "$green" "$reset" printf "%sWARN%s restart pending\n" "$yellow" "$reset" printf "plain text after reset\n"
ANSI SGR code 31 sets red text, 32 sets green text, 33 sets yellow text, and 0 resets formatting. [ -t 1 ] checks whether standard output is a terminal.
$ bash -n color-output.sh
No output means Bash parsed the variable assignments and printf calls without a syntax error.
$ bash color-output.sh ERROR disk space low OK backup completed WARN restart pending plain text after reset
The words ERROR, OK, and WARN should appear in red, green, and yellow. The final line should use the terminal default color.
$ NO_COLOR=1 bash color-output.sh ERROR disk space low OK backup completed WARN restart pending plain text after reset
NO_COLOR gives callers a simple opt-out without changing the script file.
$ bash color-output.sh > color-output.log
$ cat color-output.log ERROR disk space low OK backup completed WARN restart pending plain text after reset
Because redirected standard output is not a terminal, the script stores empty color variables before printing.
printf "%sERROR%s disk space low\n" "$red" "$reset"
Missing the reset code can leave the rest of the terminal session in the last selected color.