Linux Shell中如何检查变量是否存在呢
首先我们来看看↓:
#删除变量var
[root@localhost ~]# unset var
[root@localhost ~]# echo $var
[root@localhost ~]# var=" "
[root@localhost ~]# echo $var
[root@localhost ~]#
当变量var不存在 时,输出$var你将会得到一个空行 . 当变量var=" " ,你还是会得到一个空行 . 大多数时候,我们将无法确定一个变量到底是不存在呢?还是等于空字符串?
接下来教你一招: 语句1:${varName? Error: The variable is not defined}
上述语句的含义是如果变量varName已定义且不为空,则此语句就相当于$varName ;如果变量varName的值为空,则此语句的值也是空;但如果varName是未定义的,则此语句将返回一个错误,并显示问号?定义的错误信息Error: The variable is not defined(此信息可改成其它)
语句2:${varName:? Error: The variable is not defined} 语句2跟语句1的区别是:如果变量varName的值为空 ,此语句也返回一个错误 .
[root@localhost ~]# var=123
[root@localhost ~]# echo ${var? Error: The variable is not defined}
123
[root@localhost ~]# unset var
[root@localhost ~]# echo ${var? Error: The variable is not defined}
bash: var: Error: The variable is not defined
[root@localhost ~]# var=123
[root@localhost ~]# echo ${var:? Error: The variable is not defined}
123
[root@localhost ~]# unset var
[root@localhost ~]# echo ${var:? Error: The variable is not defined}
bash: var: Error: The variable is not defined
[root@localhost ~]# var=""
[root@localhost ~]# echo ${var:? Error: The variable is not defined}
bash: var: Error: The variable is not defined
[root@localhost ~]# echo ${var? Error: The variable is not defined}
[root@localhost ~]#
|