Linux Shell 通配符、元字符、转义符使用实例介绍(2)

加入”*” 都是作用在命令名直接。可以看到shell 元字符,基本是作用在命令上面,用作多命令分割(或者参数分割)。因此看到与通配符有相同的字符,但是实际上作用范围不同。所以不会出现混淆。

以下是man bash 得到的英文解析:

metacharacter
              A character that, when unquoted, separates words.  One of the following:
              |  & ; ( ) < > space tab
control operator
              A token that performs a control function.  It is one of the following symbols:
              || & && ; ;; ( ) | <newline>

三、shell转义符

有时候,我们想让 通配符,或者元字符 变成普通字符,不需要使用它。那么这里我们就需要用到转义符了。 shell提供转义符有三种。

字符   说明  
‘’(单引号)   又叫硬转义,其内部所有的shell 元字符、通配符都会被关掉。注意,硬转义中不允许出现’(单引号)。  
“”(双引号)   又叫软转义,其内部只允许出现特定的shell 元字符:$用于参数代换 `用于命令代替  
\(反斜杠)     又叫转义,去除其后紧跟的元字符或通配符的特殊意义。  

man bash 英文解释如下:

There are three quoting mechanisms: the escape character, single quotes, and double quotes.

实例:

[chengmo@localhost ~/shell]$ ls \*.txt
ls: 无法访问 *.txt: 没有那个文件或目录
 
[chengmo@localhost ~/shell]$ ls '*.txt'
ls: 无法访问 *.txt: 没有那个文件或目录
 
[chengmo@localhost ~/shell]$ ls 'a.txt'
a.txt
 
[chengmo@localhost ~/shell]$ ls *.txt
a.txt  b.txt

可以看到,加入了转义符 “*”已经失去了通配符意义了。

四、shell解析脚本的过程

看到上面说的这些,想必大家会问到这个问题是,有这么想特殊字符,通配符,那么 shell在得到一条命令,到达是怎么样处理的呢?我们看下下面的图:

Linux Shell 通配符、元字符、转义符使用实例介绍

 

如果用双引号包括起来,shell检测跳过了1-4步和9-10步,单引号包括起来,shell检测就会跳过了1-10步。也就是说,双引号 只经过参数扩展、命令代换和算术代换就可以送入执行步骤,而单引号转义符直接会被送入执行步骤。而且,无论是双引号转义符还是单引号转义符在执行的时候能够告诉各个命令自身内部是一体的,但是其本身在执行时是并不是命令中文本的一部分。

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/12408.html