snippetbashModeratepending
Shell script logging -- structured output with colors and levels
Viewed 0 times
loggingstderrcolorstimestampverbosedebug
terminallinuxmacos
Problem
Bash scripts with echo everywhere make it impossible to distinguish errors from info, filter output, or understand what happened when something fails.
Solution
Create logging functions with levels, colors, and timestamps. Redirect errors to stderr.
Code Snippets
Bash logging with colors and levels
#!/usr/bin/env bash
set -euo pipefail
# Colors
RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m'
BLUE='\033[0;34m' NC='\033[0m'
log() { echo -e "${BLUE}[$(date +%H:%M:%S)]${NC} $*"; }
warn() { echo -e "${YELLOW}[$(date +%H:%M:%S)] WARN:${NC} $*" >&2; }
err() { echo -e "${RED}[$(date +%H:%M:%S)] ERROR:${NC} $*" >&2; }
ok() { echo -e "${GREEN}[$(date +%H:%M:%S)] OK:${NC} $*"; }
die() { err "$*"; exit 1; }
# Usage
log "Starting deployment..."
warn "Cache will be cleared"
ok "Build complete"
die "Failed to connect to server"Revisions (0)
No revisions yet.