变量扩展
变量扩展说明
Shell中变量扩展说明如下所示:
${var}:返回${var}的内容 ${#var}:返回${var}的字符长度 ${var:offset}:返回${var}从位置offset之后开始提取字符至结束 ${var:offset:length}:返回${var}从offset之后,提取长度为length的字符 ${var#word}:返回从${var}开头开始删除最短匹配的word子符串 ${var##word}:返回从${var}开头开始删除最长匹配的word子符串 ${var%word}:返回从${var}结尾开始删除最短匹配的word子符串 ${var%%word}:返回从${var}结尾开始删除最长匹配的word子符串 ${var/oldstring/newstring}:使用newstring替换第一个匹配的字符oldstring ${var//oldstring/newstring}:使用newstring替换所有匹配的字符oldstring ${var:-word}:如果变量var的值为空或未赋值,则将word做为返回值,常用于防止变量为空或未定义而导致的异常 ${var:=word}:如果变量var的值为空或未赋值,则将word赋值给var并返回其值。 ${var:?word}:如果变量var的值为空或未赋值,则将word做为标准错误输出,否则则输出变量的值,常用于捕捉因变量未定义而导致的错误并退出程序 ${var:+word}:如果变量var的值为空或未赋值,则什么都不做,否则word字符将替换变量的值其中${var:-word}、${var:=word}、${var:?word}、${var:+word}中的冒号也可以省略,则将变量为空或未赋值修改为未赋值,去掉了为空的检测, 即运算符仅检测变量是否未赋值
变量扩展示例
[root@localhost init.d]# var="This is test string"
[root@localhost init.d]# echo $var
This is test string
[root@localhost init.d]# echo ${var}
This is test string
[root@localhost init.d]# echo ${#var} # 统计字符长度
19
[root@localhost init.d]# echo ${var:5} # 从第5个位置开始截取字符
is test string
[root@localhost init.d]# echo ${var:5:2} # 从第5个位置开始截取2个字符
is
[root@localhost init.d]# echo ${var#This} # 从开头删除最短匹配的字符 is
is test string
[root@localhost init.d]# echo ${var##This} # 从开头删除最长匹配的字符 is
is test string
[root@localhost init.d]# echo ${var%g} # 从结尾删除最短匹配的字符 is
This is test strin
[root@localhost init.d]# echo ${var%%g} # 从结尾删除最长匹配的字符 is
This is test strin
[root@localhost init.d]# echo ${var/is/newis} # 替换第一个匹配的字符
Thnewis is test string
[root@localhost init.d]# echo ${var//is/newis} # 替换所有匹配到的字符
Thnewis newis test string
[root@localhost init.d]# echo $centos # 变量未定义
[root@localhost init.d]# echo ${centos:-UNDEFINE} # 变量为空,返回UNDEFINE
UNDEFINE
[root@localhost init.d]# centos="CentOS"
[root@localhost init.d]# echo ${centos:-UNDEFINE} # 变量已经定义,返回变量本身的值
CentOS
[root@localhost init.d]# unset centos # 取消变量值
[root@localhost init.d]# echo $centos
[root@localhost init.d]# result=${centos:=UNDEFINE}
[root@localhost init.d]# echo $result
UNDEFINE
[root@localhost init.d]# echo $centos # 变量值为空,则将UNDEFINE赋值给centos
UNDEFINE
[root@localhost init.d]# unset centos
[root@localhost init.d]# echo ${centos:?can not find variable centos}
-bash: centos: can not find variable centos # 变量值为空,输出自定义错误信息
[root@localhost init.d]# centos="IS DEFINED"
[root@localhost init.d]# echo ${centos:?can not find variable centos}
IS DEFINED #变量值已定义,则输出变量值
[root@localhost init.d]# unset centos
[root@localhost init.d]# echo ${centos:+do nothing} # 变量值为空,什么都不操作输出
[root@localhost init.d]# centos="do"
[root@localhost init.d]# echo ${centos:+do nothing} # 变量已赋值,则输出自定义的消息
do nothing










