Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing flags to command via variables in bash

Tags:

bash

I have a complex script that takes variables from files and uses them to run programs (Wine specifically)

Passing options from the variables in the other file isn't working as expected:

#!/bin/bash
. settingsfile
wine $run

And in the other file:

run="run.exe -withoption \"This text\""

When I change wine $run to echo wine $run, it echos a string, which when run explicitly works fine:

#!/bin/bash
. settingsfile
wine run.exe -withoption "This text"

Edit: Running with #!/bin/bash -x shows me:

+ wine run.exe -withoption '"This' 'text"'

How do I fix this?

like image 822
J V Avatar asked Mar 03 '12 15:03

J V


1 Answers

The problem is that "This and text" are treated as separate arguments, each containing a double-quote, rather than as a single argument This text. You can see this if you write a function to print out one argument per line; this:

function echo_on_separate_lines ()
{
  local arg
  for arg in "$@" ; do
    echo "<< $arg >>"
  done
}
run="run.exe -withoption \"This text\""
echo_on_separate_lines $run

prints this:

<< run.exe >>
<< -withoption >>
<< "This >>
<< text" >>

rather than this:

<< run.exe >>
<< -withoption >>
<< This text >>

The simplest solution is to tack on an eval to re-process the quoting:

run="run.exe -withoption \"This text\""
wine $run     # or better yet:   wine "$run"

But a more robust solution is to have run be an array, and then you can refer to it as "${run[@]}":

run=(run.exe -withoption "This text")
wine "${run[@]}"

so that the quoting is handled properly from the get-go.

like image 187
ruakh Avatar answered Nov 02 '22 23:11

ruakh