Alex Rivera | Logout

Execute command containing quotes from shell variable

Asked 2012-06-18T08:35:44.880
34

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

?

Edit
Report

1 Answer

38

You need eval.

$ eval $VARIABLE
answered 2012-06-18T08:39:06.923

Your Answer