- 论坛徽章:
- 0
|
bash命令处理的12个步骤:
1、将命令行分成由固定元字符集分隔的记号;
SPACE, TAB, NEWLINE, ; , (, ), <, >, |, &
记号类型包括单词,关键字,I/O重定向符和分号。
2、检测每个命令的第一个记号,查看是否为不带引号或反斜线的关键字。
如果是一个开放的关键字,如if和其他控制结构起始字符串,function,{或(,则命令实际上为一复合命令。shell在内部对复合命令进行处理,读取下一个命令,并重复这一过程。如果关键字不是复合命令起始字符串(如then等一个控制结构中间出现的关键字),则给出语法错误信号。
3、依据别名列表检查每个命令的第一个关键字;
如果找到相应匹配,则替换其别名定义,并退回第一步;否则进入第4步。该策略允许递归别名,还允许定义关键字别名。如alias procedure=function
4、执行大括号扩展,例如a{b,c}变成ab ac
5、如果~位于单词开头,用$HOME替换~。
使用usr的主目录替换~user。
6、对任何以符号$开头的表达式执行参数(变量)替换;
7、对形式$(string)的表达式进行命令替换;
这里是嵌套的命令行处理。
8、计算形式为$((string))的算术表达式;
9、把行的参数,命令和算术替换部分再次分成单词,这次它使用$IFS中的字符做分割符而不是步骤1的元字符集;
10、对出现*, ?, [ / ]对执行路径名扩展,也称为通配符扩展;
11、按命令优先级表(跳过别名),进行命令查寻;
12、设置完I/O重定向和其他操作后执行该命令
一个命令分步处理的结果:
Further assume that a file exists called .hist537 in user alice's home directory, which is /home/alice, and that there is a double-dollar-sign variable $$ whose value is 2537 (we'll see what this special variable is in the next chapter).
Now let's see how the shell processes the following command:
ll $(type -path cc) ~alice/.*$(($$%1000))
Here is what happens to this line:
1. ll $(type -path cc) ~alice/.*$(($$%1000)) splits the input into words.
2. ll is not a keyword, so Step 2 does nothing.
3. ls -l $(type -path cc) ~alice/.*$(($$%1000)) substitutes ls -l for its alias "ll". The shell then repeats Steps 1 through 3; Step 2 splits the ls -l into two words.
4. ls -l $(type -path cc) ~alice/.*$(($$%1000)) does nothing.
5. ls -l $(type -path cc) /home/alice/.*$(($$%1000)) expands ~alice into /home/alice.
6. ls -l $(type -path cc) /home/alice/.*$((2537%1000)) substitutes 2537 for $$.
7. ls -l /usr/bin/cc /home/alice/.*$((2537%1000)) does command substitution on "type -path cc".
8. ls -l /usr/bin/cc /home/alice/.*537 evaluates the arithmetic expression 2537%1000.
9. ls -l /usr/bin/cc /home/alice/.*537 does nothing.
10. ls -l /usr/bin/cc /home/alice/.hist537 substitutes the filename for the wildcard expression .*537.
11. The command ls is found in /usr/bin.
12./usr/bin/ls is run with the option -l and the two arguments.
Although this list of steps is fairly straightforward, it is not the whole story. There are still five ways to modify the process: quoting; using command, builtin, or enable; and using the advanced command eval.
结合上面的例子,对bash命令处理的12个步骤有了进一步的理解,但是还存在一些疑惑,求大师们解答啊~
1.针对步骤一中的固定元字符集中包含 (, ), 例子中的$(type -path cc)并没有被分割成两个记号(token),从步骤7处理时把$(type -path cc)当成一个记号(token)可以看出
2.记号类型中:单词我理解的是包含命令,如echo;普通字符串,如a=123,关键字我理解的就是if,for,while等需要结合其他的字符进行操作的具有特定含义的字符串;但是不太理解做为固定元字符的I/O重定向符和分号是怎么又做为token的呢?? |
|