2015年10月7日 星期三

[Linux 常見問題] How to check if a variable is set in bash?

Source From Here
Question
How do I know if a variable is set in bash?

How-To
The following solution is incorrect:
  1. #!/bin/bash  
  2. export VAR=''  
  3. function checkVar {  
  4.     if [ -z "$VAR" ]; then  
  5.         echo "VAR is unset!"  
  6.     else  
  7.         echo "VAR is set to '$VAR'"  
  8.     fi  
  9. }  
  10.   
  11. echo "VAR is '$VAR'"  
  12. checkVar  
The execution will told you the VAR is unset which is wrong:
VAR is ''
VAR is unset!

This is because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if var='', then the above solution will incorrectly output that var is unset.

But this distinction is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.
  1. function checkVar2 {  
  2.     if [ -z ${VAR+x} ]; then  
  3.         echo "VAR is unset"  
  4.     else  
  5.         echo "VAR is set to '$VAR'"  
  6.     fi  
  7. }  
where ${VAR+x} is a parameter expansion which evaluates to the null if VAR is unset and substitutes the string "x" otherwise. For example:
[root@dcliet ~]# export VAR='test'
[root@dcliet ~]# test -z ${VAR} && echo 'VAR is unset' || echo 'VAR is set'
VAR is set
[root@dcliet ~]# unset VAR
[root@dcliet ~]# test -z ${VAR} && echo 'VAR is unset' || echo 'VAR is set'
VAR is unset
[root@dcliet ~]# [ -z ${VAR+x} ] && echo 'VAR is unset' || echo 'VAR is set'
VAR is unset
[root@dcliet ~]# export VAR=''
[root@dcliet ~]# test -z ${VAR} && echo 'VAR is unset' || echo 'VAR is set'
VAR is unset
[root@dcliet ~]# [ -z ${VAR+x} ] && echo 'VAR is unset' || echo 'VAR is set'
VAR is set
[root@dcliet ~]# export VAR='v'
[root@dcliet ~]# echo ${VAR+x}
x
[root@dcliet ~]# unset VAR
[root@dcliet ~]# echo ${VAR+x}

[root@dcliet ~]#


Supplement
Linux and Unix test command


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...