Skip to content

Instantly share code, notes, and snippets.

@alexcreek
Last active December 17, 2021 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexcreek/f28c037beb3349f220e144c747d1e37b to your computer and use it in GitHub Desktop.
Save alexcreek/f28c037beb3349f220e144c747d1e37b to your computer and use it in GitHub Desktop.
How to use getopts in bash
#!/bin/bash
usage() {
echo "Usage: $(basename "$0") [-v] [-f filename] [-g group] positional-param"
exit 1
}
if [[ "$#" -lt 1 ]]; then
usage
fi
# Prefix getops string with : to silence errors
# Option without : is just an option (-v)
# Append : to an option to accept a parameter (-f filename)
while getopts ":vf:g:" opt; do
case $opt in
v) echo "-v enabled";;
f) echo "-f was passed $OPTARG";;
g) echo "-g was passed $OPTARG";;
?) case $OPTARG in
f|g) echo "-$OPTARG missing argument"; usage;;
?) usage;;
esac
esac
done
# Remove all params processed by getopts so we can use $1 like normal
shift $((OPTIND - 1))
echo "positional parameter passed is $1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment