Search code examples
bashparametersargumentsgetopts

How to pass parameters to Bash getopts using a custom variable as opposed to ${1}, ${2} etc


I want to specify parameters (options and arguments) in a Bash variable and to pass that variable to getopts for parsing instead of the usual variables ${1}, ${2} etc. I am not sure how to do this. Often in documentation for getopts, the getopts syntax is described as follows:

Syntax
    getopts optstring name [args]

I know that optstring represents instructions for getopts on how to parse parameters and name is a variable that is to store current information under consideration by getopts (such as the value of an option's argument), but I do not know what [args] is intended to be. Is it a way to pass parameters to getopts without using the standard command line variables? If it is, how could I use this facility? If it is not, what would be a good way to pass arguments stored in, say, a space-delimited Bash variable to getopts?


Solution

  • Yes, the optional args arguments are a way to pass custom parameters. As it says in the manual:

    getopts normally parses the positional parameters, but if more arguments are given in args, getopts parses those instead.

    So if you have an array:

    myargs=(arg1 arg2 arg3)
    

    you can use:

    getopts optstring name "${myargs[@]}"
    

    to process them.

    Example:

    $ # Set positional parameters:
    $ set -- -a 1 -b
    $ getopts a:b var -a 2
    $ echo $var
    a
    $ echo $OPTARG
    2
    

    As you can see, it retrieved the value from the args I supplied to the command (2), not the positional parameters to the shell (1)