Check If a Variable is Set or Not in Bash [4 Methods]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Setting a variable is a process that initializes the variable, assigning it a value that can be accessed and used within the script. When a variable is “set,” it means that a value has been assigned to that variable. Note that, when a variable is declared with an empty string (“”), it indicates the variable has already been set. Generally, Bash offers a couple of parameters such as -v, -z, and -n to be utilized within conditional expressions to check whether a variable is set or not. In addition, the parameter expansion can be used to validate this variable check as well as to set or assign a value when the variable is not set.

In this article, I will describe 4 methods to check if a variable is set or not in Bash with different examples.

When a Variable is Considered as ‘Set’ in Bash?

In Bash scripting, a variable is considered as set or defined as long as it is declared and assigned some value. It may contain zero value or an empty string too. For instance: variable="" or variable="Linux". On the contrary, the variable that is never created, initialized, or assigned any value, is considered as an unset or undefined variable.

4 Methods to Check If a Variable is Set or Not in Bash

Bash provides several ways to check if a variable is set or not in Bash including the options -v, -z, -n, and parameter expansion, etc. Let’s explore them in detail in the following section.

1. Using “-v” Option

The -v option in the ‘if’ statement checks whether a variable is set or assigned. This option returns True if the given variable has been declared previously, regardless of its value (even if it contains an empty string). Otherwise, it states that the variable is unset.

To check if a variable is set or not, use the -v option with the “[ ]” operator using the syntax if[ -v variable ].

#!/bin/bash

#Declaring two variables
var1=""
var2="X"

#Checking if variables are set
#For var1
if [ -v var1 ];  then
echo "The variable is set with an empty string."
fi

#For var2
if [ -v var2 ];  then
echo "The variable is set with a non-empty value."
fi
EXPLANATION

This script checks if the variables var1 and var2 are defined with some values or not. If the conditions are satisfied, the script echoes the respective outputs employing the echo command.

Using '-v' option for checking if variable is setThe above image depicts that var1 and var2 both variables are set as they are assigned with values like an empty string and ‘X’ respectively.

2. Using “-z” option

The -z option checks if the variable contains a value with zero length. It returns True if the specified variable is not defined or its length is zero i.e. indicating the variable is declared and initialized with an empty string. The syntax for this option is [ -z "${variable}" ], [[ -z ${variable} ]], or [[ -z "${variable}" ]].

Let’s take a look at the following example using the [[ -z ${variable} ]] syntax to check if a variable is set or not:

#!/bin/bash

#Checking if the variable is set
if [ -z ${pqr} ]; then
echo "The variable is not set."
fi

#Assigning a value
pqr=""

#Checking if the variable is set after assigning an empty value
if [[ -z ${pqr} ]]; then
echo "The variable is set with empty string."
fi
EXPLANATION

First, when the -z option performs the conditional check, it finds that the variable ‘pqr’ is not yet declared. Thus, it echoes ‘The variable is not set.’. As well, after assigning an empty string value, the script considers the ‘pqr’ variable set i.e. having zero length, and executes ‘The variable is set with empty string.’

Checking if a variable is set or not using '-z' optionIn the above snapshot, the variable ‘pqr’ was not declared before, thus indicating it is unset. In contrast, after assigning an empty string value to the variable, it is treated as an empty variable that is already set.

3. Using “-n” option

The -n option is used in ‘if’ statement for validating if the value of a variable provided is non-empty. When a variable is assigned a non-empty value, a true expression is executed i.e. indicates the variable is set. Otherwise, the variable is unset.

To check if a variable is declared/set and not empty, use the [ -n "${variable}" ], [[ -n ${variable} ]], or [[ -n "${variable}" ]] syntax. Here’s an example utilizing the syntax [[ -n "${variable}" ]]:

#!/bin/bash

#Declaring a variable
value=55

#Checking if the variable is set
if [[ -n "${value}" ]];  then
echo "The variable is set with a non-empty value."
fi
EXPLANATION

In the above code, the condition inside [[ ]] checks if the specified variable is equal to a non-empty string. If the variable is not empty, then the condition becomes true and the script displays ‘The variable is set with a non-empty value.’

Checking if a variable is set or not using '-n' optionWhen the variable ‘value’ is found with a value of 55, it is treated as a non-empty variable already declared and set like the above image.

4. Using Parameter Expansion

Parameter expansion is an effective way to check whether a variable is set. In this effort, use the syntax ${variable+value} in conjunction with the parameters -z and -n where the expression expands to the ‘value’ if the variable is already set.

Following is an example to check if a variable is set using the if [[ -z "${variable+value}" ]] syntax with the -z option. It returns True only if the variable is not declared or not set. Otherwise, the output returns nothing.

#!/bin/bash

#Checking if the variable is set
if [[ -z "${var1+x}" ]]; then
echo "var1 is unset."
fi
EXPLANATION

Here, the -z option within the ‘if’ condition checks if the variable var1 is not set yet. As it returns a true expression, the script echoes ‘var1 is unset.’.

Checking if a variable is set using parameter expansion with '-z' optionThe above image states that the variable var1 is not set as it was never declared before.

Similarly, you can employ the parameter expansion with the -n option to check if a variable is set. In this case, use the syntax: if [[ -n "${variable+value}" ]] where “-n” returns true only when the variable is set.

How to Assign a Default Value If a Variable is Not Set

While dealing with variables, it’s very important to assign a default value to the variable that is not declared or set, otherwise, unexpected errors may occur. In Bash, there are various types of parameter expansions that you can enlist within conditional statements to accomplish this task. These are: ${variable:-default_value}, ${variable=default_value}, variable=”default_value”.
Following is an example utilizing the syntax ${variable:-default_value} where the parameter expansion substitutes the default value when a variable is not set.

#!/bin/bash

#Checking if the variable is not set initially
if [ -z "$name" ]; then
#Assigning a default value
name=${name:-N}
fi

echo "The variable ‘name’ is set with value $name."
EXPLANATION

Here, the -z option checks if the variable ‘name’ contains zero-length value i.e. an empty string or unset. If the condition is satisfied, ${name:-N} expands to ‘N’ and assigns the default value ‘N’ to the variable ‘name’. Finally, the script prints the assigned value of the variable.

Using parameter expansion to assign a default value to a variable that is not setAs you can see from the figure, the variable ‘name’ was not set initially. So, the parameter expansion assigns the default value of the variable ‘name’ with ‘N’.

You can use : ${name:=N} or name="N" instead of name=${name:-N} to do the same task.

Conclusion

The whole article enables you to check if a variable is set in Bash and how to set or assign values to a variable when it is not set. Among all the approaches, select the one that best fits your use case and programming style.

People Also Ask

Can I assign a default value to a variable without overwriting its current value?

Yes, you can use the parameter expansion syntax var=${var:="default_value"} to assign a default value to a variable without overwriting its current value.

Can I suppress errors related to unset variables in Bash?

Yes, you can suppress errors related to unset variables using the ${variable:?error_text} syntax. If the variable is unset or null, the execution will be terminated with an error message.

How do I handle errors caused by unset variables in Bash?

To handle errors caused by unset variables, you can address set -u at the beginning of the script, perform the conditional checks employing the parameters -v, -z, and -n before using variables or set default values to the variables.

What happens if I set a variable multiple times using the default assignment?

If you set a variable multiple times that is initially unset or empty using a default assignment like ${variable:-default_value}, the variable will be set to the specified default value. But if a variable is already set, then this syntax will not overwrite the actual value of the variable.

Can I set a variable within a function if it’s not set globally?

Yes, you can set the variable within a function using the local keyword even if it’s not set globally. Here’s how:

#!/bin/bash

function() {
#Setting a variable within a function
local variable=${variable:-"default_value"}
#Code to execute
}

Related Articles


<< Go Back to If Statement in Bash | Bash Conditional Statements | Bash Scripting Tutorial

Rate this post
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment