0

I am trying to pass an argument to a cmdline tool, which looks like the following:

./tool --device '(xyz-123)'

where '()' is required by the tool, and xyz-123 is stored in a variable $var where I get from another function.

If I hardcode '(xyz-123)', the tool works fine, but when I do ./tool --device '($var)', it throws an error:

  File "<string>", line 1
    tool'("xyz-123")'
                                            ^
SyntaxError: invalid syntax
Keith Zhen
  • 45
  • 1
  • 1
  • 10
  • 1
    `./tool --device '('"$var"')'` would also work, but it's very silly. – Charles Duffy Apr 15 '21 at 17:42
  • Thanks Charles, this just works! How do you interpret this? – Keith Zhen Apr 15 '21 at 17:46
  • 1
    Quoting is character-by-character. Thus, `'('` is a `(` inside single quotes, then `"$var"` expands `$var` per double-quoted rules (replacing the reference with the contents of the variable named), then a `)` in single quotes again. – Charles Duffy Apr 15 '21 at 17:49

1 Answers1

2

Use double quotes to allow variable substitution:

./tool --device "($var)"
Mike Slinn
  • 7,705
  • 5
  • 51
  • 85
  • the tool also need the '()'. how can I add this to the arg? – Keith Zhen Apr 15 '21 at 17:43
  • @KeithZhen, this answer **does** pass the `(` and `)`. The quotes really don't matter. The tool can't tell the difference between single quotes and double quotes at all. – Charles Duffy Apr 15 '21 at 17:45
  • 1
    @KeithZhen, ...the thing to remember here is that in UNIX, starting a program passes it an array of C strings as arguments. Both `'(xyz-123)'` and `"(xyz-123)"` in shell turn into the C string `"(xyz-123)"` (where the `"`s are part of C syntax, not part of the actual data at all). There's no way the program was started can tell the difference between them, because they're both represented the exact same way in memory. – Charles Duffy Apr 15 '21 at 17:47
  • got it, thanks for the explanation! – Keith Zhen Apr 15 '21 at 17:48