bash how to run command from variable


You can run command from variable using the command "eval":

eval $foo

The command eval takes argument, construct and execute command of it.

Another option is symbol "$":


Let's have following example:

foo2='echo "Hello :)"'
eval $foo

Output: Wed Jul 27 14:17:40 CEST 2016 Hello :)

It is also possible use bash's option -c which executes command from variable in separate script, that inherits file descriptors, environment variables.

bash -c "$foo"

eval "$foo" executes command in the current script, not in separate script. If you want to execute eval command in separate script, use brackets: (eval "$1").

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.