Bash Logger Function Leveled Output

Structure script output with a logger function: level filtering, stderr separation, timestamps, and color-aware terminals.

BashCli Tooling

Code

bashsnippet
44 lines
#!/usr/bin/env bash
set -euo pipefail

readonly LOG_LEVEL="${LOG_LEVEL:-info}"
declare -i VERBOSE=0
[[ "${LOG_LEVEL}" == "debug" ]] && VERBOSE=1

_timestamp() { date +'%Y-%m-%dT%H:%M:%S'; }

log() {
  local level="$1"
  shift
  local target=stdout

  case "${level}" in
    error) target=stderr ;;
    warn)  target=stderr ;;
  esac

  local prefix="[ ${level^^} ]"
  printf '%s %s %s\n' "$(_timestamp)" "${prefix}" "$*" >&"${target}"
}

log_debug() { (( VERBOSE )) && log debug "$@" || true; }
log_info()  { log info "$@"; }
log_warn()  { log warn "$@"; }
log_error() { log error "$@"; }

main() {
  log_info "开始同步目录 ${SYNC_DIR:-./data}"
  log_debug "参数列表: ${*}"

  if [[ ! -d "${SYNC_DIR:-./data}" ]]; then
    log_error "同步目录不存在,中止"
    return 1
  fi

  log_warn "磁盘剩余空间低于阈值,继续执行"
  log_info "同步完成"
}

log_debug "脚本启动于 PID $$"
main "$@"

How it works

The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.

The work is delegated to readonly, declare, log_info, log_debug and log_error, chained through 2 pipes so each stage’s output feeds the next.

4 helper functions (_timestamp, log, log_debug and log_info) keep the repeated logic out of the main flow.

The script leans on parameter expansion 9 times, using forms like ${var:-default}, ${var^^} so defaults, trimming, and casing happen inside the shell with no external tool.

The core lines of the flow

log_debug() { (( VERBOSE )) && log debug "$@" || true; }

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`readonly`, `declare`, `log_info`, `log_debug`, `log_error` must be available on the PATH environment variable; everything else is shell built-in syntax.