Created
August 24, 2017 17:38
-
-
Save abalter/4f1375985b99b84e62fcc0d63ef83174 to your computer and use it in GitHub Desktop.
Template for bash getopts argument parsing for various types of arguments.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| ### preallocate variables | |
| required= | |
| optional_hasarg= | |
| got_opt_arg=false | |
| optional_noarg=false | |
| has_default="DEFAULT" | |
| ### initialize (clear) opt parsing variables | |
| OPTIND= | |
| OPTARG= | |
| opt= | |
| while getopts "ha:b:cd:" opt; do | |
| case "$opt" in | |
| h) | |
| echo "\ | |
| usage: | |
| ------ | |
| getoptsdemo [ -h ] -a REQ [ -b OPTHAS ] [ -c ] [ -d OPTDEF ] | |
| description: | |
| ------------ | |
| This demonstrates parsing arguments with getopts | |
| optional arguments: | |
| ------------------- | |
| -h Print this help message and exit. | |
| -a REQ Required opt that takes an argument. | |
| -b OPTHAS Optional opt that takes an argument. | |
| -c Optional opt that does not take an argument. | |
| -d OPTDEF If given, sets value of has_default to OPTDEF. | |
| Otherwise, the value of has_default defaults to | |
| DEFAULT. | |
| " | |
| exit 0 | |
| ;; | |
| a) | |
| required=${OPTARG} | |
| ;; | |
| b) | |
| optional_hasarg=${OPTARG} | |
| got_opt_arg=true | |
| ;; | |
| c) | |
| optional_noarg=true | |
| ;; | |
| d) | |
| has_default=${OPTARG} | |
| ;; | |
| ?) | |
| echo "Error: did not recognize option, ${OPTARG}." | |
| echo "Please try -h for help." | |
| exit 1 | |
| ;; | |
| esac | |
| done | |
| if [[ "$required" == "" ]]; then | |
| echo "ERROR: Required option -a not set." | |
| echo "Please try -h for help." | |
| exit 1 | |
| fi | |
| echo "required: $required" | |
| if [[ "$got_opt_arg" == true ]]; then | |
| if [[ "$optional_hasarg" == "" ]]; then | |
| echo "-b option set but no argument given" | |
| echo "Please try -h for help." | |
| exit 1 | |
| else | |
| echo "optional_hasarg: $optional_hasarg" | |
| fi | |
| else | |
| echo "optional_hasarg not set" | |
| fi | |
| if [[ "$optional_noarg" == true ]]; then | |
| echo "optional_noarg set" | |
| else | |
| echo "optional_noarg not set" | |
| fi | |
| echo "has_default: $has_default" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment