3

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.

Peter Mortensen
  • 1,029
  • 1
  • 8
  • 10
A. Donda
  • 239
  • 1
  • 12
  • 3
    See [Why does my shell script choke on whitespace or other special characters?](https://unix.stackexchange.com/a/131767/65304) - in particular, the section **How do I store a command in a variable?** in @Gilles answer – steeldriver Nov 18 '18 at 00:57

2 Answers2

6

Try arrays:

NUMFMT=( --suffix=" B"   '--grouping' )
....
numfmt "${NUMFMT[@]}" 231210893
filbranden
  • 21,113
  • 3
  • 58
  • 84
1

Wouldn't that be an excellent case for an alias?

$ alias nfmtB='numfmt --suffix=" B" --grouping'
$ nfmtB 324235345656
324.235.345.656 B
RudiC
  • 8,889
  • 2
  • 10
  • 22
  • Good idea but with a little catch: command aliases are disabled in scripts by default unless enabled with `shopt -s expand_aliases`. – David Foerster Nov 18 '18 at 12:29