Using Colour in Shell Scripts for Logging

Using Colour in Shell Scripts for Logging

~ 2 min read


Why Use Colour in Shell Scripts?

I find it useful in shell scripts to define a set of logging functions to provide feedback. Adding colour to the log level helps:

  • Highlight errors, warnings, and successes
  • Improve script readability
  • Save time during debugging

Let’s walk through how to implement colour-coded logging in your shell scripts using ANSI escape codes.

ANSI Colour Codes

ANSI escape codes control formatting in terminal output, including colour. Here’s a table of common foreground and background colour codes:

Colours

Colour Foreground Code Background Code
Black 30 40
Red 31 41
Green 32 42
Yellow 33 43
Blue 34 44
Magenta 35 45
Cyan 36 46
White 37 47
Bright Black 90 100
Bright Red 91 101
Bright Green 92 102
Bright Yellow 93 103
Bright Blue 94 104
Bright Magenta 95 105
Bright Cyan 96 106
Bright White 97 107

Reset with \033[0m to end colouring.

Defining Helper Functions

A good practice is to define reusable logging functions at the top of your script:

# Colour constants
RESET="\033[0m"
RED="\033[0;31m"
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
BLUE="\033[0;34m"
BG_RED="\033[41m"
BG_YELLOW="\033[43m"

# Logging functions
log_info() {
  echo -e "${BLUE}[INFO]${RESET} $1"
}

log_success() {
  echo -e "${GREEN}[SUCCESS]${RESET} $1"
}

log_warning() {
  echo -e "${YELLOW}[WARNING]${RESET} $1"
}

log_error() {
  echo -e "${RED}${BG_YELLOW}[ERROR]${RESET} $1" >&2
}

Example Usage

log_info "Starting backup process."
if backup_files; then
  log_success "Backup completed successfully."
else
  log_error "Backup failed."
fi

This approach makes logs readable and immediately actionable, especially when scrolling through long outputs.

Tips for Usage

  • Avoid using colours in scripts that may pipe output to other commands unless optional.
  • Use colour only if the output is a terminal: if [ -t 1 ]; then ...
  • Consider allowing a --no-colour flag to disable colours in CI environments.
  • Really want to take your shell script interactions next level checkout Gum and build a TUI

Conclusion

Coloured logging can transform your shell scripts from dull to delightful. By centralising your styles into helper functions, your scripts stay clean, readable, and informative. Whether you’re debugging or sharing your work with others, a bit of colour goes a long way.

Happy scripting!

all posts →