Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute command containing quotes from shell variable [duplicate]

Tags:

bash

shell

I'm currently having problems to execute a command from a shell variable.

In general the following works as expected:

COMMAND="echo A" echo $COMMAND $COMMAND 

produces:

echo A A 

But if I do

COMMAND="su aUser -s /bin/bash -c 'echo A'" echo $COMMAND $COMMAND 

I get

su aUser -s /bin/bash -c 'echo A' Password:  A': -c: line 0: unexpected EOF while looking for matching `'' A': -c: line 1: syntax error: unexpected end of file 

If I enter the line

su aUser -s /bin/bash -c 'echo A' 

directly it works as expected.

It seems my assumption that $COMMAND is equal to entering the content as command directly is wrong.

Questions

1) Does anyone know how I can run the command from a variable?

2) What exactly is the difference between

COMMAND="command" $COMMAND 

and

command 

?

like image 559
Markus Kreusch Avatar asked Jun 18 '12 08:06

Markus Kreusch


People also ask

How do you pass a double quote into a string in a shell script?

Single quotes(') and backslash(\) are used to escape double quotes in bash shell script. We all know that inside single quotes, all special characters are ignored by the shell, so you can use double quotes inside it. You can also use a backslash to escape double quotes.

How do you pass variables in single quotes in bash?

Normally, $ symbol is used in bash to represent any defined variable. But if you use escape in front of $ symbol then the meaning of $ will be ignored and it will print the variable name instead of the value. Run the following commands to show the effects of escape character (\).


1 Answers

Arrays are useful to keep your parameters whole:

command=(su aUser -s /bin/bash -c 'echo A') 

and invoke it exactly like this:

"${command[@]}" 
like image 75
glenn jackman Avatar answered Sep 21 '22 06:09

glenn jackman