Shell编程-03-Shell中的特殊变量和扩展变量 (3)

${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

本文同步在微信订阅号上发布,如各位小伙伴们喜欢我的文章,也可以关注我的微信订阅号:woaitest,或扫描下面的二维码添加关注:

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

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