Skip to content

Instantly share code, notes, and snippets.

@aachyee
Forked from magnetikonline/README.md
Last active November 10, 2024 20:03
Show Gist options
  • Save aachyee/1f56c7bb7bbddac752772c1d8db44024 to your computer and use it in GitHub Desktop.
Save aachyee/1f56c7bb7bbddac752772c1d8db44024 to your computer and use it in GitHub Desktop.
Bash getopts template.
# Bash `getopts` template
- [Example](#example)
- [Reference](#reference)
```sh
#!/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
```sh
$ ./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
- https://man.cx/getopts(1)
- https://wiki.bash-hackers.org/howto/getopts_tutorial
- `$ help getopts`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment