1 一串命令的执行
[[email protected] log]# (a=2;echo $a)
2
[[email protected] log]# { a=2;echo $a;} #注意格式的不同,左边有空格,最右边以分号结尾
2
2 ()和{}中括号里面的某个命令的重定向只影响该命令,但括号外的重定向则影响到括号里的所有命令
[[email protected] log]# { a=10;b=100;echo $a>c;echo $b;}
100
[[email protected] log]# cat c
10
[[email protected] ~]# { a=10;b=100;echo $a;echo $b;}>c
[[email protected] ~]# cat c
10
100
3 ()只是对一串命令重新开一个子shell进行执行,{}对一串命令在当前shell执行
[[email protected] ~]# a=100
[[email protected] ~]# (a=10;echo $a)
10
[[email protected] ~]# echo $a #值没有被修改,说明()中命令在子shell中实现
100
[[email protected] ~]# a=100
[[email protected] ~]# { a=10;echo $a;}
10
[[email protected] ~]# echo $a #值已经被修改,说明{}中命令在当前shell中实现
10
4 $()和${}
命令替换:
[[email protected] ~]# echo $(ls)
anaconda-ks.cfg a.py a.sh c install.log install.log.syslog moban.sh secure test.txt
变量的实现:
[[email protected] ~]# a=1000
[[email protected] ~]# echo ${a}
1000
5 几种特殊的替换结构
${var:-string},${var:+string},${var:=string},${var:?string}
1)若变量var为空或者未定义,则用在命令行中用string来替换${var:-string},否则变量var不为空时,则用变量var的值来替换${var:-string}
[[email protected] ~]# echo $var
[[email protected] ~]# echo ${var:-bcc}
bcc
[[email protected] ~]# var=1000
[[email protected] ~]# echo ${var:-bcc}
1000
2)对于${var:=string}的替换规则和${var:-string}是一样的,所不同之处是${var:=string}若var为空时,用string替换${var:=string}的同时,把string赋给变量var:
[[email protected] ~]# echo $var
[[email protected] ~]# echo ${var:=bbc}
bbc
[[email protected] ~]# echo $var
bbc
3)${var:+string}:只有当var不是空的时候才替换成string,若var为空时则不替换或者说是替换成变量var的值,即空值
[[email protected] ~]# var=100
[[email protected] ~]# echo $var
100
[[email protected] ~]# echo ${var:+bbc}
bbc
[[email protected] ~]# echo $var
100
[[email protected] ~]# unset var
[[email protected] ~]# echo $var
[[email protected] ~]# echo ${var:+bbc}
4)${var:?string}:若变量var不为空,则用变量var的值来替换${var:?string},若变量var为空,则把string输出到标准错误中,并从脚本中退出。可利用此特性来检查是否设置了变量的值
[[email protected] ~]# echo $var
[[email protected] ~]# echo ${var:?bbc}
-bash: var: bbc
[[email protected] ~]# var=100
[[email protected] ~]# echo ${var:?bbc}
100
6 匹配和替换:
* 通配符,任意数目的任意字符
# 去掉左边
% 去掉右边
单一符号是最小匹配;两个符号是最大匹配
示例:
[[email protected] ~]# var=/var/log/messages
[[email protected] ~]# echo ${var:3:2} #取出从第3个字符开始,向后2个字符
r/
[[email protected] ~]# echo ${var:0:3} #取出前3个字符
/va
[[email protected] ~]# var=/var/log/messages
[[email protected] ~]# echo ${var/log/LOG} #把log替换成LOG
/var/LOG/messages
[[email protected] ~]# echo ${var//s/$} #两个符号是最大匹配,全部替换
/var/log/me$$age$
[[email protected] ~]# var=/var/log/messages
[[email protected] ~]# echo ${var#*/} #从左边开始,删除第一个匹配*/及其左边的
var/log/messages 字符
[[email protected] ~]# echo ${var#*m}
essages
[[email protected] ~]# echo ${var##*/} #从左边开始,删除最后一个匹配*/及其左边
messages 的字符
[[email protected] ~]# echo ${var%/*} #从右边开始,删除第一个匹配/*及其右边的
/var/log 字符