How to Print Colorful Text in a Linux Shell Script

Linux terminals understand ANSI escape codes. A color code changes the text style, and \033[0m resets it:

printf '\033[32mSuccess\033[0m\n'

This prints Success in green. Prefer printf over echo -e because printf behaves more consistently across shells.

Common colors

ColorCode
Black30
Red31
Green32
Yellow33
Blue34
Magenta35
Cyan36
White37

Use a code like \033[31m before the text and \033[0m after it.

Reusable shell script

Save this as messages.sh:

#!/bin/sh

# Disable colors with: NO_COLOR=1 ./messages.sh
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
    RED='\033[31m'
    GREEN='\033[32m'
    YELLOW='\033[33m'
    BLUE='\033[34m'
    RESET='\033[0m'
else
    RED=''
    GREEN=''
    YELLOW=''
    BLUE=''
    RESET=''
fi

print_color() {
    color=$1
    shift
    printf '%b%s%b\n' "$color" "$*" "$RESET"
}

info() {
    print_color "$BLUE" "INFO: $*"
}

success() {
    print_color "$GREEN" "OK: $*"
}

warning() {
    print_color "$YELLOW" "WARNING: $*"
}

error() {
    print_color "$RED" "ERROR: $*" >&2
}

info "Starting application"
success "Configuration loaded"
warning "Using the default configuration"
error "Could not connect to the server"

Make it executable and run it:

chmod +x messages.sh
./messages.sh

Use the functions in another script

Source the file, then call the functions:

#!/bin/sh

. ./messages.sh

info "Checking disk space"
if df -h / >/dev/null 2>&1; then
    success "Disk check completed"
else
    error "Disk check failed"
    exit 1
fi

Important details

  • Always reset the style with \033[0m, or later terminal text may keep the color.
  • Send errors to standard error with >&2, so normal output can be redirected separately.
  • The script disables colors when output is redirected or when NO_COLOR is set.
  • Use colors to support meaning, not as the only way to communicate status.

For example, this keeps a plain log file while showing colors interactively:

./messages.sh > messages.log
NO_COLOR=1 ./messages.sh