Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash quotes disable escaping

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!

like image 404
Ivan Pomortsev Avatar asked Dec 24 '22 18:12

Ivan Pomortsev


1 Answers

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'
like image 102
anubhava Avatar answered Jan 03 '23 20:01

anubhava