FUNDAMENTALS A Complete Guide for Beginners
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.
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.
❶ At first, launch an Ubuntu Terminal.
❷ Write the following command to open a file in Nano:
nano var_ex.sh
- 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
#! /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
- bash: Executes the bash scripts.
- var_ex.sh: Bash script name.
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
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 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
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
- 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.
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
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 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 |
|
|
Method 02 |
|
|
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
Related Articles
- How to Echo Variables in Bash Script? [4 Practical Examples]
- How to Use String Variables in Bash Script? [4 Cases]
- How to Append String to Bash Variable? [2 Effective Ways]
- How To Check if Bash Variable is Empty? [2 Easy Methods]
- How to List and Set Bash Environment Variables? [3 Methods]
- 2 Ways to Unset Environment Variables Using Bash Script
- 5 Methods to Check If Environment Variable is Set in Bash Script
- How to Set Bash $PATH Variable? [Easiest Configuration]
- 2 Cases to Execute Command Stored in Bash Variable
- How to Store Command Output to Bash Variable? [3 Examples]
- How to Read a File into Bash Variable? [2 Simple Methods]
- How to Write Bash Variable to File? [3 Effective Methods]
- Compare Variables in Bash Scripts [3 Practical Cases]
- Increment Variable Value in Bash Scripts [4+ Examples]
- Adding 1 to Bash Variable [3 Examples]
- Decrement Variable Value in Bash Scripts [4+ Examples]
- Addition of Bash Variable [4+ Examples]
- How to Subtract Two Bash Variables? [4+ Easy Approaches]
- How to Multiply Variable in Bash [6+ Practical Examples]
- Variable Substitution in Bash [Replace Character & Substring]
<< Go Back to Using Variables in Bash Scripting | Bash Variables | Bash Scripting Tutorial