bash getopts with multiple and mandatory options bash getopts with multiple and mandatory options bash bash

bash getopts with multiple and mandatory options


You can concatenate the options you provide and getopts will separate them. In your case statement you will handle each option individually.

You can set a flag when options are seen and check to make sure mandatory "options" (!) are present after the getopts loop has completed.

Here is an example:

#!/bin/bashrflag=falsesmall_r=falsebig_r=falseusage () { echo "How to use"; }options=':ij:rRvh'while getopts $options optiondo    case "$option" in        i  ) i_func;;        j  ) j_arg=$OPTARG;;        r  ) rflag=true; small_r=true;;        R  ) rflag=true; big_r=true;;        v  ) v_func; other_func;;        h  ) usage; exit;;        \? ) echo "Unknown option: -$OPTARG" >&2; exit 1;;        :  ) echo "Missing option argument for -$OPTARG" >&2; exit 1;;        *  ) echo "Unimplemented option: -$OPTARG" >&2; exit 1;;    esacdoneif ((OPTIND == 1))then    echo "No options specified"fishift $((OPTIND - 1))if (($# == 0))then    echo "No positional arguments specified"fiif ! $rflag && [[ -d $1 ]]then    echo "-r or -R must be included when a directory is specified" >&2    exit 1fi

This represents a complete reference implementation of a getopts function, but is only a sketch of a larger script.