eval - construct command by concatenating arguments
The eval utility shall construct a command by concatenating arguments together, separating each with a character. The constructed command shall be read and executed by the shell.
root:~# man eval
root:~# info eval
Example-1
1.1 Execute Command stored in string
root@:~# ll="ls -ltrh"
root@:~# eval $ll
drwxr-xr-x 2 root root 4.0K Dec 7 05:57 segments_24Mbps
drwxr-xr-x 2 root root 4.0K Dec 7 06:33 segments_1Mbps
-rw-r--r-- 1 root root 58 Dec 28 18:01 dns_name.txt
-rw-r--r-- 1 root root 14 Dec 28 20:06 temp_file
-rw-r--r-- 1 root root 18 Jan 3 06:44 test.txt
root@:~# eval ll
-bash: ll: command not found
As shown, eval command first evaluates the argument and then runs the command stored in the argument.
Line by Line explanation:
=> In 1st line, we have defined foo variable.
=> In 2nd line, we have defined x variable.
=> In 3rd line, we have defined y variable which consists of string '$foo'. The dollar sign must be escaped with '$'.
=> In 4th line, we have print the result of y variable.
=> In 5th line, we have re-define y variable with eval. Here, it will first evaluate $x to the string 'foo'. Now the statement y=$foo will be evaluated to y=100.
=> In 6th line, we have print the result of y variable.