Skip to content

Instantly share code, notes, and snippets.

@hflamboauto1
Forked from magnetikonline/README.md
Created July 6, 2016 11:01
Show Gist options
  • Save hflamboauto1/504f304ef5ae313e098caa193b5bbe55 to your computer and use it in GitHub Desktop.
Save hflamboauto1/504f304ef5ae313e098caa193b5bbe55 to your computer and use it in GitHub Desktop.
Template for bash getopts usage.

Template for bash getopts usage

#!/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 "$*"

# success
exit 0

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