Using unset vs. setting a variable to empty

前端 未结 4 1064
一生所求
一生所求 2020-12-23 00:37

I\'m currently writing a bash testing framework, where in a test function, both standard bash tests ([[) as well as predefined matchers can be used. Matchers ar

相关标签:
4条回答
  • 2020-12-23 00:41

    As has been said, using unset is different with arrays as well

    $ foo=(4 5 6)
    
    $ foo[2]=
    
    $ echo ${#foo[*]}
    3
    
    $ unset foo[2]
    
    $ echo ${#foo[*]}
    2
    
    0 讨论(0)
  • 2020-12-23 00:52

    So, by unset'ting the array index 2, you essentially remove that element in the array and decrement the array size (?).

    I made my own test..

    foo=(5 6 8)
    echo ${#foo[*]}
    unset foo
    echo ${#foo[*]}
    

    Which results in..

    3
    0
    

    So just to clarify that unset'ting the entire array will in fact remove it entirely.

    0 讨论(0)
  • 2020-12-23 00:54

    Based on the comments above, here is a simple test:

    isunset() { [[ "${!1}" != 'x' ]] && [[ "${!1-x}" == 'x' ]] && echo 1; }
    isset()   { [ -z "$(isunset "$1")" ] && echo 1; }
    

    Example:

    $ unset foo; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
    It's unset
    $ foo=     ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
    It's set
    $ foo=bar  ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
    It's set
    
    0 讨论(0)
  • 2020-12-23 00:55

    Mostly you don't see a difference, unless you are using set -u:

    /home/user1> var=""
    /home/user1> echo $var
    
    /home/user1> set -u
    /home/user1> echo $var
    
    /home/user1> unset var
    /home/user1> echo $var
    -bash: var: unbound variable
    

    So really, it depends on how you are going to test the variable.

    I will add that my preferred way of testing if it is set is:

    [[ -n $var ]]  # True if the length of $var is non-zero
    

    or

    [[ -z $var ]]  # True if zero length
    
    0 讨论(0)
提交回复
热议问题