Skip to content

Instantly share code, notes, and snippets.

@coxmi
Created January 29, 2020 10:24
Show Gist options
  • Save coxmi/7516c3a534b61e6d1b866083b755298e to your computer and use it in GitHub Desktop.
Save coxmi/7516c3a534b61e6d1b866083b755298e to your computer and use it in GitHub Desktop.
shell/bash get arguments alternative to getopts
#!/usr/bin/env bash
# gets arguments/options from input, using `--arg=value`, `--arg value`, or `-a value` format
# doesn't allow doubling up short args, e.g. `-ot`
positional=()
one=
two=
while [ "$#" -gt 0 ]; do
echo "$1"
case "$1" in
-o|--one) one="$2"; shift 2;;
--one=*) one="${1#*=}"; shift 1;;
-t|--two) two="$2"; shift 2;;
--two=*) two="${1#*=}"; shift 1;;
--one|--two) echo "$1 requires an argument" >&2; exit 1;;
-*) echo "unknown option: $1" >&2; exit 1;;
*) positional+=("$1"); shift 1;;
esac
done
# usage / get values in script
echo $one
echo $two
echo positional "${positional[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment