Linux

Bash shell find out if a variable has NULL value OR not

[ad_1]

I am a new to shell scripting. How do I check for NULL value in a Linux or Unix shell scripts?

You can quickly test for null or empty variables in a Bash shell script. You need to pass the -z or -n option to the test command or to the if command or use conditional expression. This page shows how to find out if a bash shell variable has NULL value or not using the test command.

To find out if a bash variable is null:

  1. Return true if a bash variable is unset or set to the null (empty) string: if [ -z "$var" ]; then echo "NULL"; else echo "Not NULL"; fi
  2. Another option to find if bash variable set to NULL: [ -z "$var" ] && echo "NULL"
  3. Determine if a bash variable is NULL: [[ ! -z "$var" ]] && echo "Not NULL" || echo "NULL"

Bash shell find out if a variable has NULL value OR not

Let us see test command syntax and examples in details. The syntax is as follows for the if command:

OR

Another option to check if bash shell variable is NULL or not

OR

OR

How to find NULL value in shell if condition on Unix

The -n returns TRUE if the length of STRING is nonzero. For example:

Example: Determine if a bash variable is NULL

The following shell script shows various possibilities with bash/sh/posix based shell:

Bash Shell Find Out If a Variable Is NULL

Conclusion

I suggest that you read the following resources for more info or see GNU/bash man page here:

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

[ad_2]

Facebook Comments

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button