bash how to run command from variable

Answer

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 "$":

$foo

Let's have following example:

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

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.