Personally, I'm using getopt, not getopts, in a function called option_handling, see my shell-script-template below.
If you want to pass args with your options you can:
Let's say your option is -z 'something'...
[...] --options hVvz: [...] -z)args="$2"; shift2;;
You want to hab a look at /usr/share/doc/util-linux/examples/getopt-parse.bash --that should come preinstalled.
Here's the template:
#!/usr/bin/env -S bash - #=============================================================================== # # FILE: <<filename here>> # # USAGE: # # DESCRIPTION: # # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: # ORGANIZATION: # CREATED: # LICENSE: BSD-3-CLAUSE # REVISION: --- #=============================================================================== #=== Init ====================================================================== set -o nounset # exit on unset variables. set -o errexit # exit on any error. set -o errtrace # any trap on ERR is inherited #set -o xtrace # show expanded command before execution. unalias -a # avoid rm being aliased to rm -rf and similar issues LANG=C # avoid locale issues VERBOSE= # Don't be verbose, unless given '-v'-option ScriptVersion="1.0" trap "cleanup" EXIT SIGTERM #=== Functions ================================================================= usage (){ echo " Usage : ${0##/*/} [options] [--] Options: -h|--help Display this message -V|--version Display script version -v|--verbose Print informational text " exit 0 } # ---------- end of function usage ---------- option_handling () { # see /usr/share/doc/util-linux/examples/getopt-parse.bash OPTS=$(getopt --name "$0" \ --options hVv \ --longoptions help,version,verbose \ --shell bash \ -- "$@") \ || (echo; echo "See above and try \"$0 --help\""; echo ; exit 1) eval set -- "$OPTS" unset OPTS while true ; do case "$1" in -h|--help) usage ;; -V|--version) echo "$0 -- Version $ScriptVersion"; exit 0 ;; -v|--verbose) VERBOSE=true shift ;; --) shift ; break ;; *) echo "I don't know what to do with \"$1\". Try $0 --help" exit 1 ;; esac done } # ---------- end of function option_handling ---------- cleanup () { # Will be called by the trap above, no need to call it manually. : } # ---------- end of function cleanup ---------- # see https://github.com/markgraf/flatten.sh about this . ~/scripting/library.bash/lazy.lib #=== Main ====================================================================== main () { option_handling "$@" } # ---------- end of function main ---------- main "$@" #=== End =======================================================================