Thursday, May 18, 2023
HomeSoftware EngineeringEasy methods to Decide if a Bash Variable is Empty

Easy methods to Decide if a Bash Variable is Empty


If you have to test if a bash variable is empty, or unset, then you should utilize the next code:

if [ -z "${VAR}" ];

The above code will test if a variable known as VAR is about, or empty.

What does this imply?

Unset implies that the variable has not been set.

Empty implies that the variable is about with an empty worth of "".

What’s the inverse of -z?

The inverse of -z is -n.

if [ -n "$VAR" ];

A brief answer to get the variable worth

VALUE="${1?"Utilization: $0 worth"}"

Check if a variable is particularly unset

if [[ -z ${VAR+x} ]]

Check the assorted potentialities

if [ -z "${VAR}" ]; then
    echo "VAR is unset or set to the empty string"
fi
if [ -z "${VAR+set}" ]; then
    echo "VAR is unset"
fi
if [ -z "${VAR-unset}" ]; then
    echo "VAR is about to the empty string"
fi
if [ -n "${VAR}" ]; then
    echo "VAR is about to a non-empty string"
fi
if [ -n "${VAR+set}" ]; then
    echo "VAR is about, probably to the empty string"
fi
if [ -n "${VAR-unset}" ]; then
    echo "VAR is both unset or set to a non-empty string"
fi

This implies:

                        +-------+-------+-----------+
                VAR is: | unset | empty | non-empty |
+-----------------------+-------+-------+-----------+
| [ -z "${VAR}" ]       | true  | true  | false     |
| [ -z "${VAR+set}" ]   | true  | false | false     |
| [ -z "${VAR-unset}" ] | false | true  | false     |
| [ -n "${VAR}" ]       | false | false | true      |
| [ -n "${VAR+set}" ]   | false | true  | true      |
| [ -n "${VAR-unset}" ] | true  | false | true      |
+-----------------------+-------+-------+-----------+
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments