So I don't know how to make getopts so that it takes every positional parameter after the argument.

What I mean by this, is the following: this is my example code:

while getopts 'a:b:' thing_here; do
        case $thing_here in
                a) part_1="${OPTARG}" ;;
                b) part_2="${OPTARG}" ;;
                *) echo "invalid option, quitting"
                        exit 1 ;;

echo "part 1 = ${part_1}"
echo "part 2 = ${part_2}"

Now what I want is the following: Input:

$: ./example_script.sh -a asd qwe zxc -b dfg 213


part 1 = asd qwe zxc
part 2 = dfg 213

But what I actually get, is the following:

part 1 = asd
part 2 =

Now I know I can do what I want to do here by enclosing the arguments as such:

$: ./example_script.sh -a 'asd qwe zxc' -b 'dfg 213'

But what I'm trying to find, is how to do this within the script and getopts itself, without having to put the quotes myself (easier for some automation).


If you don't want to enclose the args in quotes (the simplest and most robust solution), then you can't use getopts, and you have to hack something together like:

declare -A args
for arg; do
    case $arg in
        "-a") key=part_1 ;;
        "-b") key=part_2 ;;
        *)  [[ -n $key ]] || { echo "unexpected argument" >&2; exit 1; }
            args[$key]="${args[$key]}$arg "
# turn the array keys into variables
for key in "${!args[@]}"; do declare "$key=${args[$key]% }"; done
echo "part 1 => $part_1"
echo "part 2 => $part_2"

With your requirements, you cannot use getopt either. Assuming you have GNU getopt, watch what happens:

$ set --  -a asd qwe zxc -b dfg 213
$ getopt -o a:b: -- "$@"
 -a 'asd' -b 'dfg' -- 'qwe' 'zxc' '213'

Only the first word after the option is acquired as the option's argument.

I repeat, take the easy route and ensure the arguments are quoted.

  • Is there any other solution? I looked for a bit, and 'getopt' seems to be an older, but more powerful tool. I don't know if it can achieve this, but if it can, I might start learning it. – user323587 Jun 25 at 19:56
  • Look for the getopt example file on your system, it's very instructive: locate getopt-parse.bash – glenn jackman Jun 25 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.