[EnglishFrontPage] [TitleIndex] [WordIndex

Common utility functions (warn, die)

(If you were looking for option processing, see BashFAQ/035.) The following functions are frequently asked for in #bash, so we hope you find them useful.

##
# warn: Print a message to stderr.
# Usage: warn "message"
#
warn() {
  printf '%s\n' "$@" >&2
}

###
### The following three "die" functions
### depend on the above "warn" function.
###

##
# die (simple version): Print a message to stderr
# and exit with the exit status of the most recent
# command.
# Usage: some_command || die "message"
#
die () {
  local st="$?"
  warn "$@"
  exit "$st"
}

##
# die (explicit status version): Print a message to
# stderr and exit with the exit status given.
# Usage: if blah; then die "message" status_code; fi
#
die() {
  local st="$2"
  warn "$1"
  exit "$st"
}

##
# die (optional status version): Print a message to
# stderr and exit with either the given status or
# that of the most recent command.
# Usage: some_command || die "message" [status code]
#
die() {
  local st="$?"
  case "$2" in
    *[^0-9]*) :;;
    *) st="$2";;
  esac
  warn "$1"
  exit "$st"
}


CategoryShell


2012-07-01 04:05