Search code examples
linuxbashshellgetopts

send an hyphened/double-hyphened argument to getopts


I'm using getopts to get optional arguments in a shell script, and then I use them to run another script. one of the arguments I'd like to send to the other program is an optional argument (e.g --conf).

but when I'm sending it to getopts i get these error messages:

service_wrapper.sh: illegal option -- -
service_wrapper.sh: illegal option -- c
service_wrapper.sh: illegal option -- o
service_wrapper.sh: illegal option -- n
service_wrapper.sh: illegal option -- f

is there any way I can send this argument to getopts?

this is the code parsing the options:

while getopts 'p:o' OPTION
    do
        case ${OPTION} in
            o) CONF=$OPTARG;;
            p) PLATFORM=$OPTARG;;
        esac
    done

this is an example of the line I'm trying to run:

./service_wrapper.sh config -p platform -o '--full-config-data {"json_key1":"json_val1","json_key2":"json_val2"}'

EDIT:

as suggested in the comments I've printed the bash version and the args this is the output:

############################
BASH:4.2.46(2)-release
arg: config
arg: -p
arg: platform
arg: -o
arg: --full-config-data {"json_key1":"json_val1","json_key2":"json_val2"}
############################

Solution

  • Got it! After printing the args as @user1934428 suggested, I've figured out that the last argument is available to the script but not to getopts.

    I've tried to understand why and it hit me, a colon is missing after the 'o'!

    Instead of while getopts 'p:o' OPTION it should be while getopts 'p:o:' OPTION

    as noted in getopts man page:

    if a letter is followed by a colon, the option is expected to have an argument, or group of arguments, which must be separated from it by white space.

    Note: with the information above I fixed the issue and getopts got the last argument, though it parsed it by spaces, even though it was quoted. It because i sent arguments to main function like this main $@ when i shouldv'e quoted it like this main "$@".