Bash Logger Function Leveled Output

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

BashCli Tooling

Code

snippet
#!/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 "$@"