Bash ANSI Colors - How to Print Colored Text in Shell Scripts

Complete guide to using ANSI color codes in Bash shell scripts. Print colored text with echo -e, printf, tput, and $'...' syntax. Includes reusable color variable definitions.

Language Examples

Detailed Explanation

Colored Output in Bash Scripts

Bash provides several ways to output colored text using ANSI escape sequences. This guide covers all common methods and best practices.

Method 1: echo -e

The -e flag enables interpretation of escape sequences:

echo -e "\033[31mRed text\033[0m"
echo -e "\033[1;32mBold green\033[0m"

Method 2: printf

printf interprets escape sequences by default:

printf "\033[34mBlue text\033[0m\n"
printf "\033[1;33m%s\033[0m\n" "Warning message"

Method 3: $'...' Quoting

ANSI-C quoting allows direct escape sequences:

echo $'\e[35mMagenta text\e[0m'

Reusable Color Variables

Define color variables at the top of your script:

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'  # No Color (reset)

# Usage
echo -e "${RED}Error: File not found${NC}"
echo -e "${GREEN}Success: Build completed${NC}"
echo -e "${YELLOW}Warning: Low disk space${NC}"
echo -e "${BOLD}Important:${NC} Read this carefully"

Color Function Pattern

# Reusable color functions
red()    { echo -e "\033[31m$*\033[0m"; }
green()  { echo -e "\033[32m$*\033[0m"; }
yellow() { echo -e "\033[33m$*\033[0m"; }
bold()   { echo -e "\033[1m$*\033[0m"; }

# Usage
red "Error: Something failed"
green "All tests passed"
yellow "Warning: Deprecated feature"

Detecting Color Support

# Disable colors if output is not a terminal
if [ ! -t 1 ]; then
  RED=''
  GREEN=''
  YELLOW=''
  NC=''
fi

Best Practices

  1. Always reset colors with \033[0m after colored text
  2. Check if stdout is a terminal before using colors
  3. Respect the NO_COLOR environment variable convention
  4. Use color functions or variables for maintainability

Use Case

Colored Bash output is used in deployment scripts, build systems, test runners, system administration scripts, and interactive installers. Production-quality shell scripts use color to distinguish between success, warning, error, and info messages, making log output scannable and improving developer productivity.

Try It — ANSI Color Code Reference

Open full tool