1221
Comment: Not much point in using "$@" here. Changing to "$1".
|
1784
|
Deletions are marked like this. | Additions are marked like this. |
Line 8: | Line 8: |
# Usage: warn "message" | # Usage: warn "format" ["arguments"...] |
Line 11: | Line 11: |
printf '%s\n' "$1" >&2 | local fmt="$1" shift printf "script_name: $fmt\n" "$@" >&2 |
Line 23: | Line 25: |
# Usage: some_command || die "message" | # Usage: some_command || die "message" ["arguments"...] |
Line 27: | Line 29: |
warn "$1" | warn "$@" |
Line 34: | Line 36: |
# Usage: if blah; then die "message" status_code; fi | # Usage: if blah; then die status_code "message" ["arguments"...]; fi |
Line 37: | Line 39: |
local st="$2" warn "$1" |
local st="$1" shift warn "$@" |
Line 40: | Line 43: |
} ## # 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 [status code] "message" ["arguments"...] # die() { local st="$?" if [[ "$1" != *[^0-9]* ]]; then st="$1" shift fi warn "$@" exit "$st" } }}} {{{ ## # warn: Print a message to stderr. # Usage: warn "message" # warn() { printf '%s\n' "$@" >&2 |
|
Line 48: | Line 78: |
Line 49: | Line 80: |
local st="$?" case "$2" in *[^0-9]*) :;; *) st="$2";; |
local st=$? case $2 in *[^0-9]*|'') :;; *) st=$2;; |
Line 56: | Line 87: |
} | } |
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 "format" ["arguments"...] # warn() { local fmt="$1" shift printf "script_name: $fmt\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" ["arguments"...] # 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 status_code "message" ["arguments"...]; fi # die() { local st="$1" shift warn "$@" 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 [status code] "message" ["arguments"...] # die() { local st="$?" if [[ "$1" != *[^0-9]* ]]; then st="$1" shift fi warn "$@" exit "$st" }
## # warn: Print a message to stderr. # Usage: warn "message" # warn() { printf '%s\n' "$@" >&2 } ## # 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" }