Bash quotes disable escaping

2.2k views Asked by At

I want to run some command, let's name it "test" from my bash script and put there some of params from bash variable.

My script:

#!/bin/bash -x
PARAMS="-A 'Foo' -B 'Bar'"
./test $PARAMS

I've got:

+ PARAMS='-A '\''Foo'\'' -B '\''Bar'\'''
+ ./test -A ''\''Foo'\''' -B ''\''Bar'\'''

It's wrong!

Another one case:

#!/bin/bash -x
PARAMS='-A '"'"'Foo'"'"' -B '"'"'Bar'"'"
./test $PARAMS

Result is sad too:

+ PARAMS='-A '\''Foo'\'' -B '\''Bar'\'''
+ ./test -A ''\''Foo'\''' -B ''\''Bar'\'''

So, question is – how can I use bash variable as command line arguments for some command. Variable is something like "-A 'Foo' -B 'Bar'" (exactly with single-quotes) And result must be calling of program "./test" with arguments "-A 'Foo' -B 'Bar'" like this:

./test -A 'Foo' -B 'Bar'

Thanks!

1

There are 1 answers

2
anubhava On BEST ANSWER

It is safer to use BASH arrays for storing full or partial command lines like this:

params=(-A 'Foo' -B 'Bar')

then call it as:

./test "${params[@]}"

which will be same as:

./test -A 'Foo' -B 'Bar'