0

I have the following piece of code:

options=" -cm '${someVariable} -someOption'"
echo "test ${options}" 
${var1} doSomething -af ${var2} ${options}

The second line makes sure $options contains what I want. The output is correct (note there is only 2 single quotes and their position is correct):

test -cm 'abc -someOption'

The problem comes when $options is added to the third line, which runs the command itself. Bash adds more quotes to it, some being in the middle of the string:

var1 doSomething -af /path/path -cm ''\''abc' '-someOption'\'''

The output I'd like is:

var1 doSomething -af /path/path -cm 'abc -someOption'

I tried all kinds of combinations with simple and double quotes, but none work.

winter
  • 207
  • 1
  • 4
  • 13
  • 1
    Don't put quotes in variables; quotes in variables are treated as data, not shell syntax. Store the variable in an array instead, and use proper quoting when you expand it. See ["Why does shell ignore quoting characters in arguments passed to it through variables?"](https://stackoverflow.com/questions/12136948) and [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](http://mywiki.wooledge.org/BashFAQ/050) (and ignore all suggestions involving `eval` -- it is a massive bug magnet). – Gordon Davisson Mar 09 '23 at 11:36
  • Quotes aren't parsed after variables are expanded. They remain as literal. You might want to look at arrays. – konsolebox Mar 09 '23 at 13:40
  • Other potential duplicates: https://stackoverflow.com/questions/11079342/execute-command-containing-quotes-from-shell-variable, https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia – knittl Mar 09 '23 at 14:44

1 Answers1

0

As Gordon said - don't do this. c.f. BashFAQ 50 as he suggested.

You might accomplish this better with an array.
Assuming your vars are already are set -

options=( -cm $someVariable -someOption )
echo "test ${options[@]}" 
"$var1" doSomething -af "$var2" "${options[@]}"
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36