0

I am trying to combine a set of parameters, some with spaces, in a variable for reuse many places. You cannot use echo directly as in many other online examples since that does not reveal that 3 parameters are often passed instead of two, one containing a space. This question comes close to mine: Passing arguments with spaces contained in variable in bash

Is this a problem with the bash version (Raspberry PI) I am using?

Test() { for var in "$@"; do echo "$var"; done ; }
VAL=ghi
Test abc "def $VAL"
abc
def ghi
ARGS="abc \"def $VAL\""
Test $ARGS
abc
"def
ghi"

Some things I tried without success:

ARGS="abc "\""def $VAL"\"""
ARGS=$"abc \x22def $VAL\x22"
ARGS="abc \x22def $VAL\x22"
ARGS=$"abc \"def $VAL\""
ARGS="abc \"def $VAL\""
ARGS=(abc "def $VAL")
Test $ARGS
Test ${ARGS}
Test ${ARGS[@]}
Codemeister
  • 107
  • 1
  • 6
  • 2
    `dash` is not `bash` - it's a completely different shell (and has many fewer capabilities). The standard way of doing what I _think_ you want to do, at least in bash, is to use arrays: so you do `ARGS=(abc "def $VAL")` like in your last example, but then `Test "${ARGS[@]}"` (very close to your last line, but the quotes are important!) – psmears Nov 12 '21 at 16:56
  • See [Why does shell ignore quoting characters in arguments passed to it through variables?](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia) (But ignore the suggestion to use `eval` -- that way lies madness and even weirder bugs.) – Gordon Davisson Nov 12 '21 at 18:04
  • 1
    This sounds a lot like [I'm trying to put a command in a variable, but the complex cases always fail!](http://mywiki.wooledge.org/BashFAQ/050) -- you use an array `args=(abd "def $VAL")` and **quote the array expansion** like `Test "${args[@]}"` – glenn jackman Nov 12 '21 at 18:49

1 Answers1

2

How do you insert a space in some bash arguments in a variable

You quote the expansion.

Test "$ARGS"
Test "${ARGS}"

Check your scripts with shellcheck. Re-view a shell introduction.

Is this a problem with the bash version (Raspberry PI) I am using?

No.

 $"abc \x22def $VAL\x22"

$"..." is a Bash thing for translating messages using gettext. And \x22 are literally \ x 2 2 characters here, not quotes.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • This skips the part where you can't store the strings `abc` and `def ghi` in a single regular parameter and retain the distinction between the two. – chepner Nov 12 '21 at 19:02