0

I'd like to be able to store a bunch of args in bash that I want to use in a bunch of different curl commands. However, my attempts so far haven't worked in the case where the arguments have spaces in them.

I made a simple bash script to replicate the issue, getopts.sh:

#!/bin/bash

while getopts ":a:b:c:" opt; do
  case $opt in
    a)
      echo "-a was triggered, Parameter: $OPTARG" >&2
      ;;
    b)
      echo "-b was triggered, Parameter: $OPTARG" >&2
      ;;
    c)
      echo "-c was triggered, Parameter: $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

The end result I wanna get is being able to call this script in the following manner, and work as expected:

OPTS="-a foo -b bar -c baz"
./getopts.sh $OPTS -d foo
./getopts.sh $OPTS -e bar

I called this in a few different ways:

[julius@julius getopts]$ OPTS="-a foo -b bar -c baz"
[julius@julius getopts]$ ./getopts.sh $OPTS
-a was triggered, Parameter: foo
-b was triggered, Parameter: bar
-c was triggered, Parameter: baz

The first one works just as expected, however, things go south fast:

[julius@julius getopts]$ OPTS="-a foo -b bar -c \"aaa bbb\""
[julius@julius getopts]$ ./getopts.sh $OPTS
-a was triggered, Parameter: foo
-b was triggered, Parameter: bar
-c was triggered, Parameter: "aaa

I expected the c argument to be aaa bbb, however, I got "aaa Escaping the space didn't help either:

[julius@julius getopts]$ OPTS="-a foo -b bar -c aaa\ bbb"
[julius@julius getopts]$ ./getopts.sh $OPTS
-a was triggered, Parameter: foo
-b was triggered, Parameter: bar
-c was triggered, Parameter: aaa\

Heredoc is the same:

[julius@julius getopts]$ read -d '' OPTS << EOF
> -a foo
> -b bar
> -c "aaa bbb"
> EOF
[julius@julius getopts]$ ./getopts.sh $OPTS
-a was triggered, Parameter: foo
-b was triggered, Parameter: bar
-c was triggered, Parameter: "aaa

Is there a way to specify a bunch of getopt options together in a variable for reuse in bash? Why don't the above work?

Julian Grinblat
  • 161
  • 1
  • 12

0 Answers0