Bash – Prepare arguments containing quoted string in variable

bashbash-expansionstring

In a Bash script, I call a program like this in several places:

numfmt --suffix=" B" --grouping 231210893

Where the number is different every time, but the other parameters stay the same.

I would now like to move the other parameters out of the many different calls, so they are centrally defined and can be easily changed. My attempt was like this:

NUMFMT='--suffix=" B" --grouping'
...
numfmt $NUMFMT 231210893

Unfortunately, this doesn't work. The quote signs are removed at some point, and numfmt complains about an uninterpretable extra argument B. I tried plenty of other versions, using other quotes both in the definition and in the use of NUMFMT, to no avail.

How do I do this properly? And if it's not too complicated, I would also like to understand why my version doesn't work and (hopefully) another one does.

Best Answer

Try arrays:

NUMFMT=( --suffix=" B"   '--grouping' )
....
numfmt "${NUMFMT[@]}" 231210893
Related Question