How does shell parse command lines and eval commands? Does shell parse eval

Source: Internet
Author: User

How does shell parse command lines and eval commands? Does shell parse eval
1.1 shell parsing command line

The general procedure of shell reading and executing commands is as follows:

 

Take the following command as an example:

echo -e "some files:" ~/i* "\nThe date:$(date +%F)\n$name's age is $((a+4))" >/tmp/a.log

Assume that the variables "name = longshuai" and "a = 24" have been assigned before the command is executed, and the result of redirection to/tmp/a. log is:

some files: /root/inotify.sh /root/inotify.sh.oriThe date:2017-08-14longshuai's age is 28

(1). Read the input command line.

(2). parse the reference and split each word in the Command action. Each word is called a token. The token of the redirection will be saved until the extension step (5) ends, such as expansion and file truncation.

Shell has three reference methods: backslash reference, single quotation mark reference, and double quotation mark reference.

◇ Backslash escape: converts metacharacters into common literal characters. However, this can only escape the last character of the backslash.

◇ Single quotes: All characters in single quotes are converted to literal symbols. However, note: you cannot use single quotes in single quotes, even if you use backslash escape.

◇ Double quotation mark reference: converts all characters in double quotation marks to literal characters, except "\", "$", and "'" (reverse quotation marks). If "!" is enabled "! "When a historical command is referenced, the exclamation point is also excluded.

After parsing the reference, you can split words in the command line. Each part after the split is called a token. When the separator is used, not only a single command, but also a command list, the separators include: space, tab, semicolon, pipe symbol, &, &, |, redirection symbol, Parentheses, and so on.

The preceding commands are divided into the following tokens:

If pipeline symbols or command lists are combined with multiple commands, the tokens of each command are independent of each other.

(3). Check the command line structure. It mainly checks whether there is a command list and whether there are shell programming structure commands, such as if judgment command and loop structure for/while/select/until. These commands are reserved keywords, special processing is required.

(4). Extend the alias of the first token. If it is an alias, the extension returns to (2) the token decomposition process again.

(5). perform various extensions. Expansion sequence: braces extension; wave extension; parameter, variable and command replacement, arithmetic extension (if supported, this step also replaces the process); Word split; file name extension.

The reference method of different quotation marks will change the start step of the extension. As you have drawn, all quotation marks will be extended from start to end without any quotation marks, and no extension will be made when single quotation marks are used, when double quotation marks are used, the Expansion starts from the replacement of the variable.

① Extension of braces: for example,/tmp/{a, B}. log is extended to/tmp/a. log and/tmp/B. log.

② Wave number Extension: expand to the home directory. For example ~ /. Ssh Extension:/root/. ssh.

③ Variable extension: Operation and replacement of variable values. For example, replace $ a with its value 24, and replace $ {name:-longshuai} with longshuai.

④ Command replacement: This process replaces the commands in the command and replaces the result with the corresponding location of the token.

⑤ Process replacement: Replace the execution result of the process to the corresponding location. Similar to command replacement. Replace the format with "<(cmd_list)" and "> (cmd_list)", for example, "cat <(cat/etc/hosts )". The redhat series should support process replacement.

⑥ Arithmetic Extension: calculates the arithmetic value and replaces the calculation result with the corresponding position. For example, replace $ (a + 4) with 28.

After the above extensions, the following results are obtained:

7. Word Splitting: scanning the results of variable extension, command replacement, and arithmetic extension. The results without quotation marks are separated by words based on the value of $ IFS.

Note: If the extension is not performed, or the extension result is surrounded by quotation marks, the word splitting in this step is not performed.

By default, the $ IFS value is "\ t \ n". Therefore, every space, tab, or line break in the extension result is divided into two words.

This step is actually very easy to make mistakes. A typical test command. For example, if the variable name = "Ma longshuai" is used, test $ name = "longshuai" will report an error because the statement becomes test Ma longshuai = "longshuai" after the variable is extended ", because the variable is replaced, the words are split later, so that Ma and longshuai are split into two words, but they actually constitute the value of the variable name.

Therefore, to correct variable replacement and command replacement, try to enclose them with quotation marks. For example, test "$ name" = "longshuai" does not split words.

Extension of the token file name: searches for each token, and searches "*","? "And" ["symbols, and the file name extension will be found. For example, extend "/root/I *" to "/root/inotify. sh/root/inotify. sh. ori ".

(6) Remove quotation marks. After the above process, all the extensions are extended, and unnecessary quotation marks can be removed in this step.

The following result is displayed.

(7). Search and execute commands.

After word segmentation, complex command lines are composed of simple command structures. Therefore, you can search for the commands in the first token of each simple command structure with a series of Command Options. For example, the above "echo" and "-e ".

If the command does not contain any slash:

① Determine whether a shell function with this name exists. If so, call it. Otherwise, perform the next search.

② Determine whether the command is a bash built-in command. If so, execute it. Otherwise, perform the next search.

③ Search for the command from the $ PATH. If the command is found, run the command. Otherwise, an error is returned.

If the command contains one or more slashes, perform Relative Path Extension and absolute path search. If yes, run the command. Otherwise, an error is returned.

(8). Return the exit status code.

1.2 eval command

Under normal circumstances, the command will be executed when the command is searched, but if the searched command is eval, the processing method is different.

Its Syntax format is:

eval command arguments

According to the shell parsing process described above, the eval command and a series of extended options and parameters will be obtained. When searching for commands, the searched results will be the eval command, therefore, the eval Command Re-transmits all tokens except the eval command (and the eval options) to the shell for secondary parsing. Except for the token where the redirection is located, because the redirection token has been saved by shell, the file will not be truncated again.

That is to say, "command arguments" is passed to shell for parsing and execution as the eval command parameter.

The execution process is shown in:

Example:

[Root @ xuexi ~] # A = 24; name = 'long $ a' # note that single quotation marks are used to disable $ a from being extended.

If echo $ name is directly executed, the result is "long $ a", but if eval echo $ name is executed, the result is "long24 ".

[root@xuexi ~]# eval echo $namelong24

First, the shell parses the variable according to the normal process. Because the single quotation marks are used when the variable is replaced, the result of the first variable replacement of $ name is "long $ ", when the command is searched, the searched command is the eval command. Run the eval command to pass the "echo long $ a" parameter to shell again, it is equivalent to inputting "echo long $ a" in the standard input, so shell performs secondary parsing. This variable replacement replaces $ a with 24, and finally the SEARCH Command finds that it is the echo command, then we finally get long24 ".

For eval, more usage is the indirect variable $ var. In bash shell, you need to add backticks before the first $, that is, \ $ var, the reason for doing so is obvious: prevent the first shell resolution from being extended as a special variable "$.

[root@xuexi ~]# a=b[root@xuexi ~]# b=haha[root@xuexi ~]# eval echo \$$ahaha

 

Note: This article is not necessarily accurate, but based on man bash's summary. If any error occurs, make it clear. Thanks

 

Back to series article outline: http://www.cnblogs.com/f-ck-need-u/p/7048359.html

Reprinted please indicate the source: Success!

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.