-1

I am running the following bash script. When I use variables with whitespaces, when I use them, single quotes are added. It is not the result that I expect.

My scripts:

#!/bin/bash -x
KEY="x"
VALUE="b c"
VARS="$KEY=\"$VALUE\""

KEY="y"
VALUE="d e"
VARS="$VARS $KEY=\"$VALUE\""

env $VARS printenv

When I run it in debug mode I get this result

+ KEY=x
+ VALUE='b c'
+ VARS='x="b c"'
+ KEY=y
+ VALUE='d e'
+ VARS='x="b c" y="d e"'
+ env 'x="b' 'c"' 'y="d' 'e"' printenv
env: c": No such file or directory

But I need the following result:

env 'x="b' 'c"' 'y="d' 'e"' printenv

How do I prevent single quotes from being added?

When I run this line, It works well: env x="b c" y="d e" printenv

Thanks

Ansemo Abadía
  • 488
  • 3
  • 10
  • 3
    The debug mode adds the quotes to show you the results of word splitting. No quotes were actually added anywhere. – choroba Dec 03 '20 at 16:27
  • Since you're using Bash, it looks like you actually want to use an __array__ variable instead of `$VARS`. – Toby Speight Dec 03 '20 at 16:34

1 Answers1

3

You'll need to quote the $VARS variable since it contains spaces:

#!/bin/bash -x
KEY="x"
VALUE="b c"
VARS="$KEY=\"$VALUE\""

KEY="y"
VALUE="d e"
VARS="$VARS $KEY=\"$VALUE\""

env "$VARS" printenv

When to wrap quotes around a shell variable?

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • This doesn't work as desired, because the value doesn't get split into separate assignments to `x` and `y`, and the double-quotes don't get removed. What it does is set the variable `x` to `"b c" y="d e"` (including those literal double-quotes). – Gordon Davisson Dec 03 '20 at 17:59