Check If a Variable Exists in Bash Using If Statement

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

In Bash, the “if else” statement is used to control the flow of execution of the bash script statements. Within the “if else” conditional statement, a variable is an essential factor to keep the input values that help to run the script based on the variables set. Therefore, checking if a variable exists is an important task in bash scripting. There are different options including -z, -v, -n, -p, and modifiers that assist in accomplishing this task.

This article delves into four methods to check if a variable exists in Bash using the “if else” statement.

What is Variable in Bash?

A variable is a vital component of any programming language. It is a storage that stores values temporarily. These values can be any type including integers, floating numbers, strings, or any characters. In bash scripting, you can define a variable by any name you wish for or keep any value. You can access the stored values by prefixing $ using the variable name in bash. Check the syntax below:

variable_name=value
Let’s see an example of it:

number=10
website_name="Linuxsimply.com"

Here, the number and website_name are the variable names that store integer 10 and a string Linuxsimply.com respectively.

Note: You should write strings within a double quotation mark to assign them to variables.

Types of Variables

Different types of variables store different types of data in bash. Primarily, there are three types:

  1. User-defined Variables:

    The user defines this type of variable to assign a value. Users can assign integers, numbers, strings, or arrays as a variable. For example,

    name="Hello, I am mou"
  2. Environment Variables:

    Environment variables are predefined by the system. Linux bash shell controls the environment variable. These variables are always written in capital letters. Let’s see an example of an environment variable:

    echo "$USER"

    checking user name with environment variable

    It shows the current user name mou.

  3. Special Variables:
    Special variables store predefined values and it helps users to write the bash script easily. Now, see an example of using a special variable:
    #!/bin/bash
    echo "number of arguments:$#"

    Here, the $# special variable represents the number of arguments. example of special variableYou can see the number of arguments 3 in the place of the $# sign.

4 Methods to Check if a Variable Exists in Bash

To check if a variable exists in Bash, there are four approaches utilizing the “if else” statement along with various options. You can use different options like -v, -z, -n, and -p to check the presence of variables. In addition to the “-z” and “-p” options, each method includes distinct scenarios for checking the existence of a variable in Bash. Depending on the conditions set using the options, the output returns as true or false.

1. Using “-v” Operator

To check if a variable exists in the bash, you can use the -v operator that checks the variable’s existence regardless of whether the variable is empty. To check if a variable exists in Bash, follow the procedure:

  1. Open the Ubuntu terminal and create a Bash file with Nano text editor (for example: nano v_opt.sh)
  2. Now, write the following script in the Bash file:
    #!/bin/bash
    number=10
    if [[ -v number ]]; then
    echo "variable exists."
    else
    echo "variable does not exist."
    fi 
    EXPLANATION
    The -v operator is used to check if a variable exists. Here, variable number=10. If you run the script, it’ll show that the “variable exists.” If the variable was not set, the script would show “variable does not exist.”
  3. After that, make the script executable. and run it.
    checking if a variable exists in bash if statement using -v operator In this image, you can see that the variable exists.

2. Using “-z” Operator

You can check if a variable exists using the -z option within the “if else” statement. The “if else” statement returns true when the variable is empty. It checks whether the variable is empty or not. With the help of -z operator, two distinct conditions can be built to check the existence of integer variables and string variables.

A. Check If Integer Variable is Empty

To check the existence of an integer variable, you can use the -z operator within the if else statement. It checks if the variable value is empty. The below script is an example:

#!/bin/bash
number=10
if [ -z "$number" ]; then
    echo "variable does not exist."
else
    echo "variable exists."
fi
EXPLANATION

Here, the -z operator is used to check if the defined number variable is empty. If the variable is empty, it will execute that the variable does not exist. Otherwise, it will execute that the variable exists.

Now, run the script. checking if a variable exists in bash if statement using -z operator You can notice that the variable exists.

B. Check If String Variable is Set and Not Empty by Parameter Expansion

To check if a variable is set and not empty, you can adopt parameter expansion with the help of the -z operator. The syntax "${a+x}" inside the if condition replaces the string value with x if the variable a is set and non-empty. Then the -z operator evaluates to false if the variable value is not empty. Now write the following script to check if a string variable is set and not empty:

#!/bin/bash
a="Hello,how are you?"

# Check if the variable is set and not empty using parameter expansion
if [ -z "${a+x}" ]; then
    echo "String variable is unset and empty"
else
    echo "String variable is set and not empty"
fi
EXPLANATION
Here, the variable a="Hello,how are you?" holds a string. The -z "$(a+x) operator checks if the variable is set or unset and the length is zero or not.

checking if a variable exists in bash if statement using parameter expansion methodAs the variable was set and not empty, the above script executed the else block of the script.

C. Check If Integer Variable is Set and Not Empty Using Parameter Expansion

Using the -z option along with the +set modifier within the “if else” statement aids in finding variables in bash. The ${x+set} within the if condition replaces the integer value of the variable with set modifier if the variable is not empty. The -z option returns false when the variable is set and not empty. Check the example below:

#!/bin/bash
x=10
if [ -z "${x+set}" ]; then
    echo "variable x is unset."
else
    echo "variable x is set."
fi
EXPLANATION

Here, the +set modifier along with the -z option checks the presence of a variable. If you declare the variable, the output will show that the “variable is set” otherwise, it will show that the “variable is not set”.

checking variable using z option with set modifierAs the variable x is declared in the bash script, the “else” block of the script runs and the output shows that the “variable is set”.

Similiarly, the -unset modifier with the -z option checks if the variable is unset and null. If the variable x is unset and null, the {x-unset} syntax replaces the value with the unset modifier, otherwise, it is not changed. That means it will execute the else block code if you define any variable that contains a value.

#!/bin/bash
x=
if [ -z "${x-unset}" ]; then
    echo "variable x is unset."
else
    echo "variable x is set."
fi
EXPLANATION

In this bash script, the variable x is empty. Hence, it will execute the true block code variable x is unset’. When the variable is not empty, it will return the false expression.

checking variable using z option with unset modifier As the variable x doesn’t hold any value, the “if” block executes and the output shows that the “variable x is unset”.

3. Using “-n” Operator

The -n operator in Bash is utilized to check if a variable exists by verifying whether its length is non-zero. When combined with an “if else” statement, it allows you to create conditional logic based on whether a variable has been defined or not.

A. Check If Integer Variable is Not Empty in Bash

Write the following script in your Bash file to check if an integer variable is not empty:

#!/bin/bash
number=10
if [ -n "$number" ]; then
    echo "The variable exists."
else
    echo "The variable does not exist."
fi
EXPLANATION
Here, the variable number is assigned the value 10. The condition -n $number within the “if else” statement checks whether the length of the variable ‘$number’ is non-zero. 

Now, run the script.checking integer variable existence

As the length of the variable  number is non-zero, the “if” block executes and the output shows that “The variable exists.”

B. Check for Environment Variable Using “env” Command.

To check if an environment variable exists in Bash, you can use this env command. This command lists all the environment variables. Hence, the grep command is used along with env to find the defined variable in the environment variable’s list.

Note: Ensure the variable is exported in the environment variable before running the script. Otherwise, the output will execute the false code block.

Here’s an example script you can write and run:

#!/bin/bash
variable="Hello,How are you?"
if [ -n "$(env | grep -o '^variable=')" ]; then
    echo "variable is set."
else
    echo "variable is unset."
fi
EXPLANATION

Here, the environment variable named variable is  assigned with a string "Hello, How are you?". The condition -n "$(env | grep -o '^variable=')" checks whether the environment variable named variable” is set or not. The env command checks the environment variable’s existence. The grep command finds the line that starts with a variable to ensure the existence of the variable.

If you run the script, then the output will be like below.checking if environment variable existence using env command As the environment variable is set, the “if” block of the script runs and the output shows that the “variable is set.”

C. Check for Variable Using “printenv” Command

While dealing with a lot of external variables and other methods fail to check the particular environment variable, implementing this method is the best possible option. However, it is limited to environment variables, in that case, check other methods if you want to check other types of variables. To check if a variable is set using printenv command, write the following script in your Bash file:

#!/bin/bash
variable="Hello,How are you?"
if [ -n "$(printenv variable)" ]; then
    echo "variable is set."
else
    echo "variable is unset."
fi
EXPLANATION
The statement -n "$(printenv variable)" checks whether the length of the string obtained by executing the printenv command on the variable named  variable  is nono-zero. 

Before running the script, you have to set the variable to the environment variable by writing the following code in your Ubuntu terminal:

export variable="Hello,How are you?"

Now, run the script.
checking if environment variable exists in bash if statement
You can see that the environment variable is set in your system.

D. Check for Variable Using “echo” Command in Bash

It’s a beginner-friendly method to verify the presence of a variable. However, if the variable contains values separated by spaces, this method is inappropriate here. You can check the following script:

#!/bin/bash
a="Hello"
if [ -n "$(echo $a)" ]; then
    echo "variable exists."
else
    echo "variable does not exist."
fi
EXPLANATION

The -n "$(printenv variable)" statement checks whether the length of the string obtained by echoing the value of the variable $a is non-zero.

Now, run the script.

checking variable using echo commandYou can see that the output shows the defined variable a exists.

E. Using the “isset” Function to Check If a Variable is Set

The isset function checks the variable existence and if they are null. When it finds that the defined variable in the bash script and is not null, it returns the “True” as output. Check out the following script:

#!/bin/bash
isset() {
    [ -n "${!1}" ]
}
a="Hello"
if isset a; then
    echo "variable is set."
else
    echo "variable is unset."
fi
EXPLANATION

In this script, the isset function takes the name of the variable a as an argument !1. The $!1 stores the value of the variable and using the -n option checks that if the variable is non-empty, then it will execute the code inside the if block otherwise, it executes the else block code.

Now, run the script. checking variable using isset function Since the a variable is non-empty, the output shows that the variable is set.

F. Check for Variable Existence Using Parameter Expansion

You can employ the parameter expansion method with the -n option too. The ${x+set} inside the if condition replaces the variable x with set if the variable is set and not empty. The -n option returns “true” when the variable is not empty. Otherwise, the script will execute the “False” code block. Now, you can follow the script given below:

#!/bin/bash
x=10
if [[ -n ${x+set} ]];then
    echo "variable x is set"
else
    echo "variable x is not set"
fi
EXPLANATION

When you declare the variable x whether it is empty or not, it will execute the true if block code. On the other hand, it will display the else block code.

Now, run the script. checking variable using n option with set modifier After running the script, the output shows that the “variable x is set”.

The same task can be done within the “if else” statement with the -unset modifier. The -n operator with -unset modifier gives the output by checking the string length of the assigned variable. If the defined variable is null and unset, the variable value will be replaced with the unset modifier. Here, I have explained an example to check if the string variable is empty or not set. Let’s check it.

#!/bin/bash
website="Linuxsimply.com"
if [[ -n ${website-unset} ]];then
    echo "String is set"
else
    echo "String is not set"
fi
EXPLANATION

The -unset modifier along with the -n operator measures the string length and checks if the variable is empty or not. If the variable is empty, the output will execute as false. Here, “Linuxsimply.com” is the the string variable.

Now, run the script. checking variable using n option with unset modifier Since I have set the Linuxsimply.com string in the bash script. Therefore, it shows ‘string is set’.

4. Using “declare” Command

To check if a variable exists in Bash, you can use the declare command incorporating the -p option. You can check an example below to know more about it:

#!/bin/bash
a="hello"
if declare -p a &>/dev/null; then
    echo "The variable is set."
else
    echo "The variable is unset."
fi
EXPLANATION

Here, the declare command with the help of -p option checks the existence of a variable named a. Whether the variable is empty or not, if it is set in the bash script, the script will return true. Otherwise, it will execute that the variable is not set. And &>/dev/null is used to redirect both standard output and error to the “/dev/null” location.

Now, run the script. checking variable using declare The output shows that the variable is set as the variable a defined in the script.

Conclusion

I hope this article helps you understand the whole procedure of how to check a variable’s existence. Here, I have described 4 methods to verify the variable’s existence. In addition, you can employ two modifiers of parameter expansion +set and -unset along with -z and -n options to check if a variable exists in bash. Read the article attentively and follow every step to finish your task successfully.

People Also Ask

How to check if a character exists in a string in bash?

You can check it with different methods such as pattern matching or looping through the characters. The common way is to use the grep command within the if else statement. Here is an example script that checks whether ‘o’ exist in ‘Hello, World’

#!/bin/bash

string="Hello, world!"
char="o"

if grep -q "$char" <<< "$string"; then
echo "Character '$char' exists in the string."
else
echo "Character '$char' does not exist in the string."
fi

What is ‘${}’ in bash?

In Bash, the ${} notation is used for parameter expansion, allowing you to access the value of a variable. When you enclose a variable name within ${}, Bash replaces it with the value assigned to that variable.

How to read a variable in bash?

To read a variable, use the read command followed by the variable name. The basic syntax is: read variable_name
This command prompts the user to input a value, and whatever the user enters is stored in the specified variable.

Related Articles


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

5/5 - (5 votes)
Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

Leave a Comment