0

While trying to adapt this example from this answer

mycmd=(ls)               # initial command
if [ "$want_detail" = 1 ]; then
    mycmd+=(-l)          # optional flag
fi
mycmd+=("$targetdir")    # the filename

"${mycmd[@]}"

I came up with

mycmd=(python3 /tmp/test.py)
A="a value"
B="b value"
ARGS="-a ${A} -b ${B}"
mycmd+=("$ARGS")
"${mycmd[@]}"

The reason that I'm not adding each flag on its own (like mycmd+=(-l) in the original example) is because I have 9 of them so I'm trying to avoid adding each flag and its value on a separate line (18 extra lines).

The problem is that test.py receives the arguments as a single string. I also suspect I'll have other issues because the values of my arguments might contain spaces (which can probably be solved with ARGS="-a \"${A}\" -b \"${B}\""?).

$ bash -x /tmp/test.sh
+ mycmd=(python3 /tmp/test.py)                          
+ A='a value'                                           
+ B='b value'                                           
+ ARGS='-a a value -b b value'                          
+ mycmd+=("$ARGS")                                      
+ python3 /tmp/test.py '-a a value -b b value'          
usage: test.py [-h] -a A -b B                           
test.py: error: the following arguments are required: -b
DeepSpace
  • 979
  • In your ls example, it should be mycmd+=(-- "$targetdir") btw, not mycmd+=("$targetdir"), especially if you can't guarantee that $targetdir won't start with -. – Stéphane Chazelas Aug 17 '20 at 09:50

1 Answers1

3

I'm not adding each flag on its own ...

That's the problem. You kinda defeated the whole point of using arrays here by squashing the separate arguments into one.

I'm trying to avoid adding each flag and its value on a separate line...

Then do something like:

mycmd+=(-a "$A") 
# or
mycmd+=(-a "$A" -b "$B")
muru
  • 72,889