quotes - bash quoting issue when using bash -c with more than one argument -


first want apologize bad title, problem best illustrated through following example:

this command works fine, although doesn't make lot of sense so.

sudo bash -c 'pwd 2>/dev/null' 

but when put in variable, , :

command="sudo bash -c 'pwd 2>/dev/null'" (set -xv; ${command}) 

i quoting unmatching error:

+ sudo bash -c ''\''pwd' '2>/dev/null'\''' 2>/dev/null': -c: line 0: unexpected eof while looking matching `'' 2>/dev/null': -c: line 1: syntax error: unexpected end of file 

the problem here seems space between pwd , 2>/dev/null, following works:

command="sudo bash -c 'pwd'" (set -xv; ${command}) 

the problem appears when put tailing whitespace after pwd

what doing wrong here? , how solve ? in advance.

you should @ least use array, acts second layer of proper quoting, instead of flat string:

my_command=(sudo bash -c 'pwd 2>/dev/null') "${my_command[@]}" 

however, should rethink why feel necessary store command in first place. function better idea:

my_command () {     sudo bash -c 'pwd 2> /dev/null' }  my_command 

Comments