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
lsexample, it should bemycmd+=(-- "$targetdir")btw, notmycmd+=("$targetdir"), especially if you can't guarantee that$targetdirwon't start with-. – Stéphane Chazelas Aug 17 '20 at 09:50