How to check if a variable is set in Bash

Overview

In this shot, we will learn how to check if a variable is set or not in Bash. This is useful when we want to know whether a variable is set across many files.

We can check this using the -v option.

Syntax

-v variable_name
Syntax

Parameter and return value

This option takes a variable name and returns a boolean value. It returns true if the value is set for a variable. It returns false if the value is not set.

Let's take a look at an example of this.

Example

x=10
#Check if the variable is set
if [[ -v x ]];
then
echo "variable x is already set"
else
echo "variable x is not set"
fi

Explanation

  • Line 1: We declare and initialize the x variable.
  • Line 4: We check if variable x is set or not using the -v option.
  • Lines 6–8: We display appropriate statements according to the boolean value returned in Line 4.

Note: If we execute the code snippet, it displays variable x is already set, as line 4 returns true.