eval | c="echo"; a1="Hello, "; a2="World!"; eval $c $a1 $a2
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:
${!varname}Examples
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:
Hi!
Comments
Post a Comment