Bash quotes disable escaping

I want to run some command, call it "test" from my bash script and put some of the parameters from the bash variable in there.

My script:

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

      

I have:

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

      

It is not right!

Another case:

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

      

The result is also sad:

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

      

So the question is, how can I use a bash variable as command line arguments for some command. The variable is something like "-A 'Foo' -B 'Bar'" (with single quotes exactly) And the result should be a call to the program "./test" with arguments "-A" Foo '-B' Bar '" in the following way:

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

      

Thank!

+3


source to share


1 answer


It is safer to use BASH arrays to store full or partial instructions such as:

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

      

then call it like:



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

      

which will be the same as:

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

      

+8


source







All Articles