元字符
1、什么是 元字符
元字符属于shell这门编程语言的语法,被shell解释器解释的'特殊字符'
ps:grep命令解释的特殊符号是正则表达式中的特殊符号,正则与元字符中的符号都是'公用'的,但是表示的意义截然不同
#shell中的元字符被bash解释器解释
#正则表达式被命令解释
2、为何要用元字符
让命令的操作更加丰富
3、如何用元字符
#1、~:家目录
#2、``:取命令的运行结果
$():支持嵌套
[root@Centos7 test]# res=$(ls $(pwd))
[root@Centos7 test]# echo $res
#3、!
#3.1 !历史命令
#3.2 !$取上一条命令的参数
#3.3 取反
对命令的结果取反:
[root@Centos7 test]# ! pwd
/test
[root@Centos7 test]# echo $?
1
[root@Centos7 test]# find /test ! -name "*.txt"
#[]表示一个范围,!和^在[]中表示取反,一个[]表示一个字符
#一位数字.txt
[root@Centos7 test]# ls /test/[0-9].txt
#批量创建,以A到Z开头的.png文件
[root@web01 mnt]# touch {a..z}.png
[root@web01 mnt]# touch {A..Z}.png
[root@web01 mnt]# touch {1..10}.png
[root@web01 mnt]# touch 11.txt aa.png
#取反
[root@web01 mnt]# ll [!a-z].png
[root@web01 mnt]# ll [!A-Z].png
[root@Centos7 test]# ls [!0-9].txt
[root@Centos7 test]# ls [^0-9].txt
#查找
[root@web01 mnt]# ll [A-Z].png #不含a.png
[root@web01 mnt]# ll [a-z].png #不含Z.png
[root@web01 mnt]# ll [0-9].txt #不能写成[0-10]
#查找多位开头
[root@web01 mnt]# ll [1-9][1-9].txt #查找以2位数字开头的 .txt文件或目录
[root@web01 mnt]# ll [a-Z][a-Z].png #查找以2位字母开头的 .png文件或目录
#特殊文件名
[root@web01 opt]# touch a1b.txt a2b.txt a3b.txt a-b.txt a+b.txt
[root@web01 opt]# ll a[1-+]b.txt # - 符号只能放在最左和最右,[或者1或者2]
ls: cannot access a[1-+]b.txt: No such file or directory
[root@web01 opt]# ll a[a+-]b.txt
[root@web01 opt]# ll a[!-a+]b.txt
#4、@没有特殊意义
#5、#注释
原则:给关键代码加注释
地方:
1、代码的正上方单独一行
2、代码正后方
#6、$
取变量的值:
x=111
echo $x
取命令的运行结果
echo $(pwd)
#通配符
bash解释器中,*任意多个字符。.表示任意一个字符。正则中,*任意多个字符。?表示任意一个字符
#小括号
[root@Centos7 ~]# echo $x
[root@Centos7 ~]# (x=1)
[root@Centos7 ~]# echo $x #因为shell是进程,进程之间是隔离的
[root@Centos7 ~]# umask
0022
[root@Centos7 ~]# (umask 666;touch {a..c}.txt) #当前shell中umask不变
[root@Centos7 ~]# touch d.txt
[root@Centos7 ~]# ll
---------- 1 root root 0 Aug 25 18:53 a.txt
---------- 1 root root 0 Aug 25 18:53 b.txt
---------- 1 root root 0 Aug 25 18:53 c.txt
-rw-r--r-- 1 root root 0 Aug 25 18:53 d.txt
#:
: true,真
[root@Centos7 ~]# :
[root@Centos7 ~]# echo $?
0
[root@Centos7 ~]# true
[root@Centos7 ~]# echo $?
0
# ?
?匹配任意一个字符,*表示任意多个字符
[root@Centos7 test]# touch 1111.txt 11.txt 1.txt 2.txt 3.txt aaaaa.txt
[root@Centos7 test]# ls *.txt
1111.txt 11.txt 1.txt 2.txt 3.txt aaaaa.txt
[root@Centos7 test]# ls ?.txt
1.txt 2.txt 3.txt
[root@Centos7 test]# ls ??.txt
11.txt
[root@Centos7 test]# ls ???.txt
ls: cannot access ???.txt: No such file or directory
[root@Centos7 test]# ls ????.txt
1111.txt
[root@hass-11 test]# ls [1-9].txt
1.txt 2.txt 3.txt
总结
() :数组
(()) :
{} :指定变量的界限
[] :判断
$() :优先执行
$(()) :
${} :
$[[]] :