Skip to content

Instantly share code, notes, and snippets.

@gregmark
Last active November 29, 2022 21:24
Show Gist options
  • Save gregmark/c918efea922c00890bcdb7e25b0e551e to your computer and use it in GitHub Desktop.
Save gregmark/c918efea922c00890bcdb7e25b0e551e to your computer and use it in GitHub Desktop.
Bash Options -- gregmark, mark 1
#!/bin/bash
# me
# ------------------------------------------------------------------------------
script=$(basename $0)
script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &>/dev/null && pwd )"
script_path="${script_dir?}/${script}"
# error & usage
# ------------------------------------------------------------------------------
# google err function
gerr() {
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $*" >&2
}
err () {
_rc=$1
if [[ "${1}" =~ ^[1-9][0-9]*$ ]]; then
shift
(echo -n ERROR; [[ $# -ge 1 ]] && echo ": $@" || echo) >&2
return ${_rc}
else
echo $@
fi
return 0
}
usage () {
err $@ && _rc=$? && echo $_rc
echo
cat <<-EOF
usage: ${script} [options]
EOF
exit ${_rc:-0}
}
# option defaults
# ------------------------------------------------------------------------------
declare true=1 false=0
declare -A vars_default=(
# boolean
[bool]=${false}
[verbose]=${false}
[dryrun]=${false}
[debug]=${false}
# optargs
[mutually]="foo"
[exclusive]="bar"
[string]=""
)
array_copy() {
set -- "$(declare -p $1)" "$2"
eval "$2=${1#*=}"
}
declare -A vars
array_copy vars_default vars
# option parsing
# ------------------------------------------------------------------------------
read_optarg () {
_params="$@"d
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
echo $2
else
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
}
PARAMS=""
while (( "$#" )); do
case "$1" in
-b|--bool)
vars[bool]=${true} ;
shift ;
;;
-m|--mutually)
vars[mutually]=${true} && vars[exclusive]=${false} ;
shift ;;
;;
-e|--exclusive)
vars[exclusive]="true" && vars[mutually]= && shift
;;
-s|--string)
vars[string]="$(read_optarg $@)" ;
shift 2 ;
;;
-v|--verbose)
vars[verbose]=${true} ;
shift ;
;;
-n|--dryrun)
vars[dryrun]=${true} ;
shift ;
;;
-d|--debug)
vars[debug]=${true} ;
shift ;
;;
-h|--help)
usage 0 && shift
;;
-*|--*=) # unsupported flags
echo "Error: Unsupported flag $1" >&2
exit 1
;;
*) # preserve positional arguments
PARAMS="$PARAMS $1" && shift
;;
esac
done
eval set -- "$PARAMS"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment