Eval in shell

Source: Internet
Author: User

Function Description: Recalculate the parameter content.

Grammar: Eval [parameter]

Additional instructions: Eval can read a series of parameters and then execute them according to the characteristics of the parameters.

Parameter: Parameters are not limited. They are separated by semicolons.

 

1. the eval command will first scan the command line for all replications, and then execute the command. This command is used for variables that cannot be implemented by one scan. This command scans variables twice. These variables that require two scans are sometimes called complex variables.

2. eval can also be used to display simple variables at different times.

NAME = ZONE

Eval echo $ NAME is equivalent to echo $ NAME

3. Two scans

Test.txt content: hello shell world!

Myfile = "cat test.txt"

(1) echo $ myfile # result: cat test.txt

(2) eval echo $ myfile # result: hello shell world!

From (2) we can know that the variable is replaced by the first scan, and the second scan executes the commands contained in the string.

4. Obtain the last parameter

Echo "Last argument is $ (eval echo \ $ #)"

Echo "Last argument is $ (eval echo $ #)"

 

Shell also provides eval commands. Like other familiar scripting languages, it uses its parameters as command execution. At first glance, it may wonder why shell should provide two mechanisms for dynamically Executing command strings, however, after careful analysis, we found that shell eval is very different from other languages.

1. although functions in shell can be returned through return, return here is equivalent to exit. It can only be a state value for testing, but cannot return complex results like other languages, the processing result can only be obtained after '', $ () is output to the standard output.

2. eval in shell

2.1 function processing results cannot be obtained. As 1 said, all commands and function processing results can only be obtained through, therefore, it is impossible to use eval in other languages to obtain output after dynamically generated code is executed.

2.2 eval Nesting is meaningless. In other languages, eval ("code") can be used to execute (execute the return of dynamically generated code ), in shell, eval simply executes the following eval command as a command string, without nesting, which is replaced by commands.

Extended reading: detailed explanation of the eval command use example materials www.linuxso.com

The role of eval is to execute command line processing again, that is, to process a command line twice. It takes some effort to make good use of this command. Let me give you two examples.

1. Example 1: Use the eval technique to implement the shell control structure

Use the eval technique to implement the shell control structure.

[Root @ home root] # cat myscript1

QUOTE:
#! /Bin/sh
Evalit (){
If [$ cnt = 1]; then
Eval $ @
Return
Else
Let cnt = "cnt-1"
Evalit $ @
Fi
Eval $ @
}
Cnt = $1
Echo $ cnt | egrep "^ [1-9] [0-9] * $">/dev/null
If [$? -Eq 0]; then
Shift
Evalit $ @
Else
Echo 'error !!! Check your input! '
Fi
[Root @ home root] #./myscript1 3 hostname
Home
Home
Home
[Root @ home root] #./myscript1 5 id | cut-f1-d''
Uid = 0 (root)
Uid = 0 (root)
Uid = 0 (root)
Uid = 0 (root)
Uid = 0 (root)
Note: bash has two special variables that save the parameter list.

$ * Stores the string groups separated by the delimiter specified by $ IFS.
$ @, The parameter list is saved as is, that is, "$1" "$2 "...

Here I use function recursion and eval to implement the for structure.
When eval $ @ is executed, it goes through the following steps:
Step 2, split into eval $ @
Step 2: extend $ @ to hostname
Step 2: Find the built-in command eval
Repeat command line processing. In Step 1, locate the hostname command and execute it.

Note: it may be assumed that why eval is used? Run the command directly at $.

Example 2: A Typical error example

Error! Here is a typical example.

[Root @ home root] # a = "id | cut-f1-d ''"
[Root @ home root] # $
Id: Invalid option # f
Run 'id # help' to obtain more information.
[Root @ home root] # eval $
Uid = 0 (root)

If the command line is complex (including pipelines or other characters), an error occurs when you directly execute the $ a string. The analysis is as follows.
$ A is processed in step 1 -- parameter extension, that is, Pipeline Analysis is skipped, so "|", "cut", "-f1 ", "-d" is changed to the parameter of the id command. Of course, an error occurs.
However, eval is used to process the obtained "id", "|", "cut", "-f1 ", "-d" these strings are processed by the command line again. This time, the pipeline is analyzed correctly.

All in all: ensure that your command or script design can be correctly handled through the command line. Skipping any step may cause unexpected errors!

Example 3: Set the ls color display of the system

Eval $ (dircolors-B/etc/dircolors)

The eval statement notifies shell to accept eval parameters and run them again through all the steps processed by the command line.
It allows you to write scripts to create command strings at will, and then pass them to shell for execution;
$ () Is the output string of the command to be returned.
The dircolors command generates the bash code for setting the environment variable LS_COLORS according to the/etc/dircolors configuration file. The content is as follows:

[Root @ localhost root] # dircolors-B> tmp
[Root @ localhost root] # cat tmp
LS_COLORS = 'no = 00: fi = 00: di = 01; 34: ln = 01 ;......
Export LS_COLORS
# The configuration file is not specified here, So dircolors generates code based on the preset database.
Its output is passed to shell by the eval command.

Eval is a flexible application of Bash Shell Command Line Processing rules, and then constructs "intelligent" commands to implement complex functions.
The command mentioned above is a very common application of eval. It repeats the command line parameter passing process and purely executes the command.
In fact, it is a challenge of bash and a required skill for senior bash programmers.

References: http://www.linuxso.com/command/eval.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.