Bash Check if Variable is Set
A variable is often referred to as a box containing a name and the contents. A simple command, e.g., “echo Hello $Var_Name’ will print “Hello…the value of the variable as defined’. Bash will print nothing if the box is empty or not created. That is why it is important to make sure whether a variable is set properly or not while creating any bash script.
Variables can be categorized into two parts:
- Defined Variables
Variables which are properly created or initialized, are known as Defined Variables. These may have zero value or an empty string. - Undefined Variables
Variables which are never created or initialized, are known as Undefined Variables.
To confirm whether a variable is set or not in Bash Scripting, we can use -v var or -z ${var} options as an expression with the combination of ‘if’ conditional command.
Syntax
Following are the syntaxes of boolean expression which can be used to check if the variable is set:
The boolean expression returns ‘True’ if the variable is set and ‘False’ if the variable is not set.
Following are the examples to check whether a variable is set or not:
Using -v Option
Output
Here, variable ‘A’ is defined and assigned a value of 100 and hence is considered as ‘set variable’. For variable ‘B’, we have not defined or assigned any value. As a result, the variable ‘B’ is not considered as ‘set variable’.
Using -z Option
Output
Note: There is a difference between an unset variable and a variable with a null value.
Check out the following example demonstrating that the variable with a null value can be a set variable.
Example
Output
These are the commonly used methods that can be used to check if a variable is set or not.