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

4

36

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.

Corunna answered 15/1, 2018 at 10:26 Comment(1)
Your logic is upside down, -z is true when the string is empty.Alice
P
52

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
Peculation answered 15/1, 2018 at 10:33 Comment(0)
B
23
if [[ -z "$list_Data" ]]
then
  echo "Empty"
else
  echo "Not empty"
fi

Try it like this. (Added $ and switched cases.)

Bethea answered 15/1, 2018 at 10:29 Comment(0)
S
10

You can use any of the below in Bash shell find out if a variable has NULL value OR not

my_var="DragonBallz"
if [ -z "$my_var" ]
then
      echo "\$my_var is NULL"
else
      echo "\$my_var is NOT NULL"
fi

(or)

my_var=""
if test -z "$my_var" 
then
      echo "\$my_var is NULL"
else
      echo "\$my_var is NOT NULL"
fi

(or)

[ -z "$my_var" ] && echo "NULL"
[ -z "$my_var" ] && echo "NULL" || echo "Not NULL"

(or)

[[ -z "$my_var" ]] && echo "NULL"
[[ -z "$my_var" ]] && echo "NULL" || echo "Not NULL"

(or)

var="$1"
if [ ! -n "$var" ]
then
    echo "$0 - Error \$var not set or NULL"
else
    echo "\$var set and now starting $0 shell script..."
fi
Sufferance answered 11/6, 2020 at 19:35 Comment(0)
C
10

I wasn't expecting this solution, when all above solutions failed for me, this one worked for me

if [[ "$is_always_execute" == null ]];
then
    is_always_execute=false;
fi
Clop answered 17/6, 2022 at 14:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.