29

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

?

Markus Kreusch
  • 2,031
  • 3
  • 18
  • 32

2 Answers2

39

Arrays are useful to keep your parameters whole:

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

and invoke it exactly like this:

"${command[@]}"
glenn jackman
  • 223,850
  • 36
  • 205
  • 328
32

You need eval.

$ eval $VARIABLE
Igor Chubin
  • 57,130
  • 8
  • 114
  • 135
  • 2
    Ok that works. Any hints what $COMMAND exactly does and why it is different to eval? – Markus Kreusch Jun 18 '12 at 09:04
  • 3
    Avoid eval whenever possible, it has a reputation for being a source of weird bugs. If you must use it, at least double-quote the variable (i.e. eval "$VARIABLE"). Loosely speaking, $VARIABLE does some, but not all, of the normal parsing before executing; eval $VARIABLE does some parsing and then parses it again; eval "$VARIABLE" parses it exactly once. But you're really better off using something like @glenn's answer. – Gordon Davisson Jun 18 '12 at 15:42
  • `eval $VARIABLE` has bugs that would be avoided by using `eval "$VARIABLE"`. To demonstrate those bugs, try `VARIABLE=$'printf " - %s\\n" "first line" " * " "third line"'` and compare `eval`ing it both ways in a non-empty directory. – Charles Duffy Sep 30 '21 at 15:40