Shell Script : How to check if variable is null or no

TheRight picture TheRight · Jan 15, 2018 · Viewed 10.9k times · Source

I want to check if variable is null or no.

My code is :

    list_Data="2018-01-15 10:00:00.000|zQfrkkiabiPZ||04|
            2018-01-15 10:00:00.000|zQgKLANvbRWg||04|
            2018-01-15 10:00:00.000|zQgTEbJjWGjf||01|
            2018-01-15 10:00:00.000|zQgwF1YJLnAT||01|"

    echo "list_Data"

    if [[ -z "list_Data" ]]
    then
    echo "not Empty"
    else
    echo "empty"
    fi

The Output is :

2018-01-15 10:00:00.000|zQfrkkiabiPZ||04|
2018-01-15 10:00:00.000|zQgKLANvbRWg||04|
2018-01-15 10:00:00.000|zQgTEbJjWGjf||01|
2018-01-15 10:00:00.000|zQgwF1YJLnAT||01|
empty

The problem that the varible contain values but i have always empty message please help.

Answer

RavinderSingh13 picture RavinderSingh13 · Jan 15, 2018

Try following, you should change from -z to -n as follows and add $ to your variable too.

if [[ -n "$list_Data" ]]
then
    echo "not Empty"
else
    echo "empty"
fi

Explanation: From man test page as follows(It checks if a variable is having any value or not. If it has any value then condition is TRUE, if not then it is FALSE.)

   -n STRING
          the length of STRING is nonzero