How to Check if Variable Is Set in Bash

Nilesh Katuwal Feb 02, 2024
  1. Check if Variable Is Set Using -v in Bash
  2. Check if Variable Is Set Using -z in Bash
  3. Check if Variable Is Set or Not by Assigning a Null Value in Bash
How to Check if Variable Is Set in Bash

We must first define a variable and give it a value to set a variable.

The value can be null, but it must be assigned. There is a distinction between an unset variable and a null variable.

Unlike most common programming languages, Bash does not have a built-in function for determining if a variable is set or not. Still, it does have a capability for doing so.

In Bash Scripting, we can use the -v var or -z $var options as an expression with the if conditional command to confirm if a variable is set or not.

[[-v Name_Of_Variable]]
[[-z Name_Of_Variable]]

If the variable is set, the boolean expression returns True, else it returns False.

Check if Variable Is Set Using -v in Bash

We’ll check if a variable is set using the -v Variable now.

Let’s define a variable X with a value of 5. If the variable is set, it will return Variable 'X' is set..

#!/bin/bash

X=5  
 
if [[ -v X ]];  
then  
echo "Variable 'X' is set."  
else  
echo "Variable 'X' is not set."  
fi  

Output:

Variable 'X' is set.

Since we defined the variable and assigned the value, it worked as expected. Let’s look at another example.

#!/bin/bash
     
if [[ -v Y ]];  
then  
echo "Variable 'Y' is set."  
else  
echo "Variable 'Y' is not set."  
fi 

Output:

Variable 'Y' is not set.

Since we did not define any variable Y, the output says variable Y is not set.

Check if Variable Is Set Using -z in Bash

We’ll check if a variable is set using -z Variable now.

Let’s define a variable X with a value of 5. If the variable is set, it will return Variable 'X' is set..

#!/bin/bash
X=5  
 
if [[ -z ${X} ]];  
then  
echo "Variable 'X' is not set."  
else  
echo "Variable 'X' is set."  
fi  

Here, the first if condition will return False, the second will return True, and Variable 'X' is set. will print.

Output:

Variable 'X' is set.

It worked as expected since we defined the variable and assigned it a value. Consider another example.

#!/bin/bash

if [[ -z ${X} ]];  
then  
echo "Variable 'X' is not set."  
else  
echo "Variable 'X' is set."  
fi 

Output:

Variable 'X' is not set.

Check if Variable Is Set or Not by Assigning a Null Value in Bash

We’ll check if a variable is set using -v Variable now.

Let’s define a variable X with a null value as X="". If the variable is set, it will return Variable 'X' is set..

#!/bin/bash

X=""     
if [[ -v X ]];  then  
   echo "Variable 'X' is set."  
else  
   echo "Variable 'X' is not set."  
fi 

Output:

Variable 'X' is set.

As we can see, even if a null value is assigned to a variable, it will show up as set after checking.

Related Article - Bash Variable