红帽linux之shell扩展

463 阅读2分钟

「这是我参与11月更文挑战的第25天,活动详情查看:2021最后一次更文挑战

使用shell扩展匹配用户名

命令行扩展:
Bash有多种扩展命令行的方式,包括模式匹配、主目录扩展、字符串扩展和变量
替换等。
其中最强大的是路径名称匹配功能,在过去被称为“通配”(globbing)。
Bash通配功能通常称为“通配符”。
使用元字符(metacharacters)扩展文件与路径名称的匹配功能。
常用元字符与匹配:
[fu@VM-0-3-centos ~]$ mkdir glob;cd glob
[fu@VM-0-3-centos glob]$ touch alfa bravo charlie delta dog easy echo
[fu@VM-0-3-centos glob]$ ls
alfa  bravo  charlie  delta  dog  easy  echo
[fu@VM-0-3-centos glob]$ ls a*
alfa
[fu@VM-0-3-centos glob]$ ls  *a*
alfa  bravo  charlie  delta  easy
[fu@VM-0-3-centos glob]$ ls [ac]*
alfa  charlie
[fu@VM-0-3-centos glob]$ ls ???
dog
[fu@VM-0-3-centos glob]$ ls ????
alfa  easy  echo

大括号(brace)扩展:

大括号扩展用于生成任意字符串,快速创建文件或目录。
大括号扩展可以互相嵌套
双句点语法(..)可扩展成一个序列,使得 {m..p} 扩展为 m n o p。
[fu@VM-0-3-centos glob]$ echo {Sunday,Monday,Tuesday,Wednesday}.log
Sunday.log Monday.log Tuesday.log Wednesday.log
[fu@VM-0-3-centos glob]$ echo file{1..3}.txt
file1.txt file2.txt file3.txt
[fu@VM-0-3-centos glob]$ echo file{a..c}.txt
filea.txt fileb.txt filec.txt
[fu@VM-0-3-centos glob]$ 
[fu@VM-0-3-centos glob]$ echo file{a,b}{1,2}.txt
filea1.txt filea2.txt fileb1.txt fileb2.txt

变量扩展: 通过变量,可以从命令行或在shell脚本内轻松访问和修改存储的数据。


```csharp
[fu@VM-0-3-centos ~]$ USERNAME=operator
[fu@VM-0-3-centos ~]$ echo $USERNAME

为了避免因其它shell扩展而引起的错误,可以将变量的名称放在大括号中, 如${VARIABLENAME}。

[fu@VM-0-3-centos ~]$ USERNAME=operator
[fu@VM-0-3-centos ~]$ echo ${USERNAME}

命令替换(substitution):

$(command):命令替换
[fu@VM-0-3-centos ~]$ echo Today is $(date +%M) minutes past $(date +%l%p)
Today is 27 minutes past 2PM

command:也表示命令替换,不推荐使用。 命令替换中使用反引号(`)的缺点:

  1. 反引号很容易与单引号混用
  2. 反引号不能用于嵌套

防止参数被扩展: 在Bash shell中,许多字符有特殊含义。

为了防止shell在命令行的某些部分上执行shell扩展,可以为字符和字符串加
引号或执行转义。
反斜杠(backslash,\)是Bash shell中的转义字符。
它可以防止紧随其后的字符被扩展。

[fu@VM-0-3-centos ~]$ echo The value of $HOME is your home directory
The value of /home/fu is your home directory
[fu@VM-0-3-centos ~]$ echo The value of \$HOME is your home directory
The value of $HOME is your home directory
如果要保护较长的字符串,则使用单引号(')或双引号(")来括起字符串。
单引号将阻止所有shell扩展。
双引号则阻止大部分shell扩展。
双引号可以阻止通配和shell扩展,但依然允许命令和变量替换。