下面的shell命令,bash是怎样进行词法分析和执行的?

假设这样一个简单的sh文件:

#!/bin/bash

a=

b=${a:- ; 456}

echo $b

使用bash执行的时候,bash的词法分析、语法分析、以及执行过程是怎样的?

比如:b=${a:- ; 456}这一行,究竟拆分成几个单词?以及变量扩展后的执行过程?

关于bash分词、以及变量扩展的规则有一些困惑。多谢解答!

参考文章:
bash手册中文版
Bash命令行处理

问题补充:

  1. 空格和分号均为bash元字符,那么在第一步分词阶段,b=${a:- ; 456} 是分割为 以下5个单词吗?单词1: b=${a:- ;单词2:空格;单词3:分号;单词4:空格;单词5:456} 是这样吗?如果不是,第一步分解成哪几个单词?

阅读 2.9k
2 个回答

${ 开始的 parameter expansion 是有特殊处理的。其中两个匹配的大括号之间的内容不会被分开。

Parameter Expansion
The `$' character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.
When braces are used, the matching ending brace is the first `}' not escaped by a backslash or within a quoted string, and not within an embedded arithmetic expansion, command substitution, or parameter expansion.
sequenceDiagram
    participant L as 词法分析器
    participant S as 语法分析器
    participant V as 变量扩展和执行
    participant O as 输出结果
    L->>S: 分析脚本
    S->>V: 解析语句
    V->>O: 执行命令
    O-->>L: 输出结果
+-------------+     +-------------+     +------------------+     +-----------+
| 词法分析器  | --> | 语法分析器  | --> | 变量扩展和执行   | --> | 输出结果  |
+-------------+     +-------------+     +------------------+     +-----------+
| b=${a:- ; 456} -->  b=${a:- ; 456} --> b=; 456           --> | ; 456     |
+-------------+     +-------------+     +------------------+     +-----------+
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题