Differences between revisions 1 and 18 (spanning 17 versions)
Revision 1 as of 2009-12-07 00:52:08
Size: 368
Editor: ozgw
Comment:
Revision 18 as of 2012-07-27 09:56:35
Size: 1221
Editor: geirha
Comment: Not much point in using "$@" here. Changing to "$1".
Deletions are marked like this. Additions are marked like this.
Line 2: Line 2:
== How do I process options in a bash script? ==

For example, how do I code my bash script to accept a bunch of options like
== 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.
Line 7: Line 6:
foobar -a --busy --include something ##
# warn: Print a message to stderr.
# Usage: warn "message"
#
warn() {
  printf '%s\n' "$1" >&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 "$1"
  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"
}
Line 9: Line 58:

First up, there are some [[http://www.gnu.org/software/libtool/manual/libc/Argument-Syntax.html][GNU and POSIX standards]] for how to do this.

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' "$1" >&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 "$1"
  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

BashFAQ/101 (last edited 2020-02-04 18:35:41 by GreyCat)