SoFunction
Updated on 2025-03-10

Example of usage of eval in shell

Function description: Tell the shell to take out the parameters of eval and re-operate to find the contents of the parameters.
Syntax: eval [parameters]
Supplementary Note: Eval can read a series of parameters and then execute them according to the characteristics of the parameters themselves.
Parameters: There is no limit on the number of parameters, and they are separated from each other by semicolons.
1. Scan it twice before executing the command line, and calculate the contents of the parameters again.

Copy the codeThe code is as follows:

[root@localhost blue]# a="ls |more"
[root@localhost blue]# $a                                           #ls

Think of | and more as parameters, rather than displaying files by page
Copy the codeThe code is as follows:

ls: cannot access |more: No such file or directory
[root@localhost blue]# eval $a                                                                                                                        �

and execute them again
Copy the codeThe code is as follows:

1

2

3

[root@localhost test]# a="123"
[root@localhost test]# echo '${'"a"'}'                        
${a}
[root@localhost test]# eval echo '${'"a"'}'
123 

Get the last parameter
Copy the codeThe code is as follows:

[root@localhost blue]# echo 'eval echo \$$#' > last
[root@localhost blue]# cat last
eval echo \$$#
[root@localhost blue]# ./last 1 2 3 4
4

In addition, other advanced usages will be added!
eval is a flexible application of Bash Shell command line processing rules, thereby constructing "intelligent" commands to achieve complex functions.
The command mentioned above is one of the very common applications of eval. It repeats the command line parameter passing process once, and executes commands purely.
In fact, it is a difficult point in bash and a compulsory skill for advanced bash programmers.