Optional option argument with getopts

This workaround defines ‘R’ with no argument (no ‘:’), tests for any argument after the ‘-R’ (manage last option on the command line) and tests if an existing argument starts with a dash. # No : after R while getopts “hd:R” arg; do case $arg in (…) R) # Check next positional parameter eval nextopt=\${$OPTIND} … Read more

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/bash rflag=false small_r=false big_r=false … Read more

Why does getopts only work the first time?

You need to add this line at top of your function: OPTIND=1 Otherwise successive invocation of the function in shell are not resetting this back since function is being run in the same shell every time. As per help getopts: Each time it is invoked, getopts will place the next option in the shell variable … Read more

Using getopts inside a Bash function

As @Ansgar points out, the argument to your option is stored in ${OPTARG}, but this is not the only thing to watch out for when using getopts inside a function. You also need to make sure that ${OPTIND} is local to the function by either unsetting it or declaring it local, otherwise you will encounter … Read more