Bash How to Run Command from Variable

Bash How to Run Command from Variable

You can run the command from variable using the command “eval”:

eval $foo

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

Another option is the symbol “$”:

$foo

Let’s have the following example:

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

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

It is also possible to use bash’s option -c which executes commands from variables in a separate script, that inherits file descriptors, environment variables.

bash -c "$foo"

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

Leave a Comment