Skip to content

Instantly share code, notes, and snippets.

@goodmami
Created August 14, 2016 04:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goodmami/f16bf95c894ff28548e31dc7ab9ce27b to your computer and use it in GitHub Desktop.
Save goodmami/f16bf95c894ff28548e31dc7ab9ce27b to your computer and use it in GitHub Desktop.
Processing command-line arguments in Bash
#!/bin/bash
die() { echo "$1"; exit 1; }
usage() {
cat <<EOF
Usage: getargs [--help] [OPTION...] ARGUMENT...
Example usage of useful conventions for command-line argument parsing.
Options:
-h, --help display this help message
-a, --alpha set alpha to true
-b, --beta=VAL set beta to VAL
Arguments:
ARGUMENT one or more nonsense arguments
EOF
}
# Default values
alpha=false
beta=
# Option parsing
while [ $# -gt 0 ]; do
case "$1" in
--*=*) a="${1%%=*}"; b="${1#*=}"; shift; set -- "$a" "$b" "$@" ;;
-h|--help) usage; exit 0; shift ;;
-a|--alpha) alpha=true; shift ;;
-b|--beta) beta="$2"; shift 2 ;;
--) shift; break ;;
-*) usage; die "Invalid option: $1" ;;
*) break ;;
esac
done
# Deal with positional arguments here: $1, $2, etc.
echo "alpha: $alpha; beta: $beta args: $@"
# $ ./getargs.sh
# alpha: false; beta: args:
# $ ./getargs.sh -a
# alpha: true; beta: args:
# $ ./getargs.sh -ab
# Usage: getargs [--help] [OPTION...] ARGUMENT...
#
# [...]
#
# Invalid option: -ab
# $ ./getargs.sh --alpha
# alpha: true; beta: args:
# $ ./getargs.sh --beta=1
# alpha: false; beta: 1 args:
# $ ./getargs.sh --beta 1
# alpha: false; beta: 1 args:
# $ ./getargs.sh --alpha --beta 1
# alpha: true; beta: 1 args:
# $ ./getargs.sh -a -b 1
# alpha: true; beta: 1 args:
# $ ./getargs.sh -a -b 1 one two
# alpha: true; beta: 1 args: one two
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment