Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active May 25, 2024 01:30
Show Gist options
  • Save magnetikonline/0e44ab972a7efa3ac138 to your computer and use it in GitHub Desktop.
Save magnetikonline/0e44ab972a7efa3ac138 to your computer and use it in GitHub Desktop.
Bash getopts template.

Bash getopts template

#!/bin/bash -e

function usage {
	cat <<EOF >&2
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
EOF

	exit 1
}

# init switch flags
c=
d=

while getopts :a:b:cdh optKey; do
	case $optKey in
		a)
			a=$OPTARG
			;;
		b)
			b=$OPTARG
			;;
		c)
			c=:
			;;
		d)
			d=:
			;;
		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