How to execute command stored in a variable?
Unix shells operate a series of transformations on each line of input before executing them. For most shells it looks something like this (taken from the bash
manpage):
- initial word splitting
- brace expansion
- tilde expansion
- parameter, variable and arithmetic expansion
- command substitution
- secondary word splitting
- path expansion (aka globbing)
- quote removal
Using $cmd
directly gets it replaced by your command during the parameter expansion phase, and it then undergoes all following transformations.
Using eval "$cmd"
does nothing until the quote removal phase, where $cmd
is returned as is, and passed as a parameter to eval
, whose function is to run the whole chain again before executing.
So basically, they're the same in most cases, and differ when your command makes use of the transformation steps up to parameter expansion. For example, using brace expansion:
$ cmd="echo foo{bar,baz}"
$ $cmd
foo{bar,baz}
$ eval "$cmd"
foobar foobaz
If you just do eval $cmd
when we do cmd="ls -l"
(interactively and in a script) we get the desired result. In your case, you have a pipe with a grep without a pattern, so the grep part will fail with an error message. Just $cmd
will generate a "command not found" (or some such) message.
So try use eval and use a finished command, not one that generates an error message.