Test for a Bash variable being unset, using a function

后端 未结 7 1312
逝去的感伤
逝去的感伤 2020-12-07 11:37

A simple Bash variable test goes:

${varName:?    \"${varName} is not defined\"}

I\'d like to re-use this, by putting it in a function. How

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 11:51

    This function tests for variables that ARE CURRENTLY set. The variable may even be an array. Note that in bash: 0 == TRUE, 1 == FALSE.

    function var.defined {
        eval '[[ ${!'$1'[@]} ]]'
    }
    
    # Typical Usage of var.defined {}
    
    declare you="Your Name Here" ref='you';
    
    read -p "What's your name: " you;
    
    if var.defined you; then   # Simple demo using literal text
    
        echo "BASH recognizes $you";
        echo "BASH also knows a reference to $ref as ${!ref}, by indirection."; 
    
    fi
    
    unset you # have just been killed by a master :D
    
    if ! var.defined $ref; then    # Standard demo using an expanded literal value
    
        echo "BASH doesn't know $ref any longer";
    
    fi
    
    read -s -N 1 -p "Press any key to continue...";
    echo "";
    

    So to be clear here, the function tests literal text. Everytime a command is called in bash, variables are GENERALLY 'swapped-out' or 'substituted' with the underlying value unless:

    • $varRef ($) is escaped: \$varRef
    • $varRef is single quoted '$varRef'

提交回复
热议问题