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

ColourForeground CodeBackground Code
Black3040
Red3141
Green3242
Yellow3343
Blue3444
Magenta3545
Cyan3646
White3747
Bright Black90100
Bright Red91101
Bright Green92102
Bright Yellow93103
Bright Blue94104
Bright Magenta95105
Bright Cyan96106
Bright White97107

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 →