Bash eval builtin command

Updated: 10/11/2017 by Computer Hope

About eval

eval is a builtin command of the Bash shell. It concatenates its arguments into a single string, joining the arguments with spaces, then executes that string as a bash command. It's similar to running bash -c "string", but eval executes the command in the current shell environment rather than creating a child shell process.

The eval command is not used very often in bash. In other shells, it can be used in scripts as a way to get the value of a variable whose name is not known until the script is run. In bash, however, this can be accomplished with variable indirection using the syntax:


For more information, see variable indirection in bash.

In general, eval is useful if you need to evaluate a string an additional time before it is evaluated by bash. It may also be useful if you need to programmatically construct a command that contains special operators or reserved words.


eval [argument ...] 


c="echo"; a1="Hello, "; a2="World!"; eval $c $a1 $a2

Assign strings to variables c, a1, and a2. Then, use eval to evaluate those arguments and join them into a single string, with a space between each. Then, run that string as a command, "echo Hello, World!". Output:

Hello, World!
cmd1="cmd2"; cmd2="echo Hi!"; eval \${$cmd1}

Here, eval is used to provide an additional layer of evaluation before a command is executed. Specifically, eval evaluates \${$cmd1} to "${cmd2}" (the backslash escapes the dollar sign, so that it evaluates as a literal $ character), then passes that string to bash for execution. The command ${cmd2} is evaluated by bash using parameter expansion (see parameter expansion in bash for more information). The end result is the command "echo Hi!". Output:


exec — Destroy the current shell and replace it with a new process.