How to Check If Bash Variable Exists? [2 Effective Methods]

Bash (Bourne Again SHell) is a widely-used command line interface for Unix-like systems. Working with Bash variables is crucial for shell scripting, as they enable data storage and processing. However, ensuring a variable exists before use is essential to prevent errors and unwanted outcomes. In this article, I will explore techniques to check if a Bash variable exists. Let’s dive into the world of Bash variables and discover how to effectively validate their existence, ensuring smooth execution and avoiding potential pitfalls.

Key Takeaways

  • Learning the process of comparing with NULL and using the -z flag to check the existence of a Bash variable.
  • Knowing about the usage of declare command to check if a Bash variable exists.

Free Downloads

2 Methods to Check If Bash Variable Exists

In this section, I have discussed two effective methods to check whether the Bash variable exists. The first one is by comparing with NULL, and the second one is by using the declare command.

You can read our Comparative Analysis of Methods to distinguish between these three methods and pick the best one for your needs.

Method 01: Comparing With NULL to Check If the Variable Exists

In this method, I have checked whether the variable exists by comparing it with the NULL. I have shown two cases of this method. The case 1 is about using the -v flag and case 2 is about using the -z flag.

Case 01:  Using “-v” Flag to Check If the Variable Exists in Bash Script

The -v flag checks whether the variable exists or not. It is a straightforward process to check the existence of a variable. In this example, I have developed a script that will check whether variables a and b exist. To do so, follow the below procedures.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a file in Nano:

nano var_ex.sh
EXPLANATION
  • nano: Opens the nano text editor.
  • var_ex.sh: Bash script name.

❸ Copy the script mentioned below:

#!/bin/bash

a=130 # a variable is set

if [[ -v a ]]; #checks whether a exists

then
echo "variable named a is already set" #if exists print this message

else
echo "variable a is not set" #if does not exist then print this message

fi

#b variable is not set

if [[ -v b ]]; #checks whether b exists

then
echo "variable named b is already set" #if exists print this message

else
echo "variable b is not set" #if does not exist then print this message

fi
EXPLANATION

#! /bin/bash ‘#!’, is called shebang or hashbang. It indicates the interpreter to be used for executing the script, in this case, it’s bash. Then the a=130 command sets the variable a. Afterward, the if [[ -v a ]]; command checks whether the variable a exists. Then the then echo “variable named a is already set” command will print a message if the variable a exists. If the variable a does not exist then the else echo “variable a is not set” command will print a message. And finally, the fi command terminates the if condition. The subsequent part of the Bash script is similar to the first part of that script.

❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.

❻ Run the script by the following command:

bash var_ex.sh
EXPLANATION
  • bash: Executes the bash scripts.
  • var_ex.sh: Bash script name.

The var_ex.sh script has checked whether variable a and b exists or not.The above image shows that I have checked whether variables a and b exist or not using the var_ex.sh Bash script.

Case 02: Check If Variable is Set Using the “-z” Flag in Bash Script

In this case, I have developed a Bash script to check whether a variable exists or not using the -z flag. The -z flag simply calculates the length of a variable. If the variable is NULL or does not exist, it returns a zero as exit status. To do the task, follow the below Bash script.

You can follow the steps of case 01 of method 01, to write and save the file.

Script (var_z.sh) >

#!/bin/bash

a=10 #variable a is set
# a: variable is set

if [[ -z ${a} ]]; #checks the length of variable a

then
echo "variable a is not set" #print this message if the variable a is NULL or does not exist

else
echo "variable named a is already set" #print this message if the variable a is not NULL or exists

fi

# b: variable is not set
if [[ -z ${b} ]]; #checks the length of variable b

then
echo "variable b is not set" #print this message if the variable b is NULL or does not exist

else
echo "variable named b is already set" #print this message if the variable b is not NULL or exists

fi
EXPLANATION

The a=10 command set the variable a. Afterward the if [[ -z ${a} ]]; command checks whether the length of the variable a is zero means it is a NULL character. This command will return a zero exit status if the variable a does not exist. Afterward, the then echo “variable a is not set” command prints a message if the condition gives a zero exit status. If not, then the else echo “variable named a is already set” prints a message. Then fi terminates the if condition.

The subsequent part of the Bash script is similar to the first part of this script.

Run the script by the following command:

bash var_z.sh

The var_z.sh Bash script has checked whether variables a and b exist or not.The above image shows that the var_z.sh Bash script has checked whether variables a and b exist or not.

Case 03: Check Whether an Environment Variable Exists or Not

Sometimes, you might need to check whether an environment variable exists. You can achieve the task by using the grep command with the if condition. To know more, follow the below script.

You can follow the steps of case 01 of method 01, to write and save the file.

Script (env.sh) >

#!/bin/bash

env | grep PWD > /dev/null #grep command will look for the value of the PWD env variable

if [ $? -eq 0 ] #here $? Holds the exit status of the previous grep command. If the grep command finds the value of PWD then the exit status will be zero

then

echo "The value of Environment variable is: $PWD"

else

echo "Environment variable does not exist."

fi
EXPLANATION

At first, grep command will look for PWD environment variable. If it finds it, the exit status will be zero, which will be saved on $?. Then the if condition will compare the exit status with zero. If it matches, it will print a confirmation message. Otherwise not.

Execute the following commands to make the file executable.

chmod +x env.sh
EXPLANATION
  • chmod: Changes the permissions of files and directories.
  • +x: Argument with the chmod command to add the executable permission.
  • env.sh: File that you want to make executable.

Run the script by using the following command:

./env.sh

The Bash script has found the value of the PWD env variable and printed it on the terminal.The Bash script has found the value of the PWD env variable and printed it on the terminal.

Method 02: Check If the Variable is Set Using “declare” Command

Using the declare command to check the existence of a Bash variable is another approach. I have developed a Bash script using declare command in the condition of the if condition. The declare command only looks for the attribute and value of the Bash variable. To do the task, follow the below Bash script.

You can follow the steps of case 01 of method 01, to write and save the file.

Script(declare.sh) >

#!/bin/bash

#var_1 does not exist
if declare -p var_1 &>/dev/null; #declare command looks for the value and attribute of the var_1 variable

then

echo "var_1 exists." #if the var_1 variable exists, it prints the message

else

echo "var_1 does not exist." #if the var_1 variable does not exit, it prints the message

fi

#var_2 exists

var_2=4 #the var_2 variable is set

if declare -p var_2 &>/dev/null; #declare command looks for the value and attribute of the var_2 variable

then

echo "var_2 exists." #if the var_2 variable exist, it prints the message

else

echo "var_2 does not exist." #if the var_2 variable does not exist, it prints the message

fi
EXPLANATION

The if declare -p var_1 &>/dev/null; command means that the condition of the if condition is to look for the attribute and the value of the var_1 variable. If these are found, it returns a zero, which means that the echo “var_1 exists.” command will be executed and print a message. If these are not found then the else echo “var_1 does not exist.” command will print a message on the terminal. After that, the fi terminates the if condition. The subsequent part of the Bash script is similar to the first part of this script.

Run the script by the following command:

bash declare.sh

The declare.sh Bash script has checked whether variables a and b exist or not using the declare command.The above image shows the declare.sh Bash script has checked whether variables a and b exist or not using the declare command.

Comparative Analysis Between the Two Methods

In this article, I have discussed two different methods to check whether a variable exists or not. A comparative analysis between these two above methods is given below.

Methods Pros Cons
Method 01
  • Straight-forward process.
  • Do not generate any error message.
  • Provide limited information about the variable.
Method 02
  • Can provide detailed information about the variable.
  • It may take extra time to be executed.
  • It generates an error message.

If you look for straight forward process, you can choose method 01. But if you need to get additional information, you can use method 02.

Conclusion

In conclusion, there are two effective methods for checking if a Bash variable exists: using the -v or -z flag and the declare command. The -v or -z flag offers a simple approach, while the declare command provides more detailed information. Choose the method based on your specific needs and Bash version compatibility. Mastering these methods enhances scripting capabilities and ensures reliable variable handling in the Bash shell environment.

People Also Ask

How do you check if a variable is not empty in Bash?
To check this, use the -z option to check if the specified variable is empty in Bash. Use the -n option to check if the specified variable is empty in Bash. And, use the “=” operator to check if the specified variable is empty or not. And use the ! operator to check whether the specified variable is empty.
Which is not a valid variable in Bash?
The shell variable can contain only letters(a to z or A to Z), numbers(0 to 9), or an underscore character(_). The variable can not start with a number.
How do you check if a variable contains a string Bash?
The simplest method is to compare the substring to the string while enclosing it in the wildcard symbol (asterisk) *. A wildcard can stand in for 0 characters, 1 character, or more. The substring is present in the string if the test returns true.
How do you check if a variable is empty or not?
The variable’s status is determined by the empty() method. If the variable is present and not empty, this method returns false; otherwise, it returns true.

Related Articles


<< Go Back to Using Variables in Bash Scripting | Bash Variables | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment