Skip to content

Instantly share code, notes, and snippets.

@clw-dm
Forked from magnetikonline/README.md
Created June 20, 2019 16:11
Show Gist options
  • Save clw-dm/59f8d56be9b927cbb825ce483c7b4872 to your computer and use it in GitHub Desktop.
Save clw-dm/59f8d56be9b927cbb825ce483c7b4872 to your computer and use it in GitHub Desktop.
Bash getopts usage template.

Bash getopts usage template

#!/bin/bash -e

function usage {
	cat <<EOM
Usage: $(basename "$0") [OPTION]...

  -a VALUE    argument description
              line two
              line three
  -b VALUE    argument description
  -c          switch description
              line two
  -d          switch description
              line two
              line three
              line four
  -h          display help
EOM

	exit 2
}

# init switch flags
c=0
d=0

while getopts ":a:b:cdh" optKey; do
	case "$optKey" in
		a)
			a=$OPTARG
			;;
		b)
			b=$OPTARG
			;;
		c)
			c=1
			;;
		d)
			d=1
			;;
		h|*)
			usage
			;;
	esac
done

shift $((OPTIND - 1))

echo "Processed:"
echo "a=$a"
echo "b=$b"
echo "c=$c"
echo "d=$d"
echo

echo "A total of $# args remain:"
echo "$*"

Example

$ ./getopts.sh -cd -a foo -b 'bah blah' -- more params
Processed:
a=foo
b=bah blah
c=1
d=1

A total of 2 args remaining:
more params

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment