Skip to content

Instantly share code, notes, and snippets.

@wware
Last active February 1, 2018 21:31
Show Gist options
  • Select an option

  • Save wware/27fae7168d4282577ca78ea697578b3e to your computer and use it in GitHub Desktop.

Select an option

Save wware/27fae7168d4282577ca78ea697578b3e to your computer and use it in GitHub Desktop.
Apparently getopt(1) for Bash is buggy, according to http://mywiki.wooledge.org/BashFAQ/035#getopts, where getopts is OK. But it's not that hard to just write scripts that don't use either of them.
#!/bin/bash
help() {
echo "Bash script that parses cmd line args without getopt(s)"
echo "Adapted from https://stackoverflow.com/questions/192249"
echo " -h, --help print this help message"
echo " -f, --foo set FOO variable"
echo " -b, --bar set BAR variable"
echo " -d, --debug enable debug (doesn't really do anything here)"
echo " <anything else> becomes a positional argument"
echo ""
echo "Example:"
echo " \$ $0 -d -f 123 -b 456 abcde fghijkl"
echo " FOO = 123"
echo " BAR = 456"
echo " DEBUG = YES"
echo " \$1 = abcde"
echo " \$2 = fghijkl"
echo " \$3 = "
echo ""
}
POSITIONAL=()
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-h|--help)
help
exit 0
;;
-f|--foo)
FOO="$2"
shift
shift
;;
-b|--bar)
BAR="$2"
shift
shift
;;
-d|--debug)
DEBUG=YES
shift
;;
*)
POSITIONAL+=("$1")
shift
;;
esac
done
# positional parameters become $1, $2, $3... respectively
set -- "${POSITIONAL[@]}"
echo FOO = "${FOO}"
echo BAR = "${BAR}"
echo DEBUG = "${DEBUG}"
echo \$1 = "$1"
echo \$2 = "$2"
echo \$3 = "$3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment