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 basically 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 with 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.
Types of Variables
Different types of variables store different types of data in bash. Primarily, there are three types:
- 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"
- 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"
It shows the current user name mou.
- Special VariablesSpecial 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.
You 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 two 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.
Method 01: 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 the variable is empty. To check if a variable exists in Bash, follow the procedure:
- Open the Ubuntu terminal and create a Bash file with Nano text editor (for example:
nano v_opt.sh
) - 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
EXPLANATIONThe-v
operator is used to check if a variable exists. Here, variablenumber=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.” - After that, make the script executable. and run it.
In this image, you can see that the variable exists.
Method 02: 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.
Case 01: Check for Integer Variable
To check the existence of an integer variable, you can use the -z
operator within the if else
statement. The below script is an example:
#!/bin/bash
number=10
if [ -z "$number" ]; then
echo "variable does not exist."
else
echo "variable exists."
fi
Here, the -z
operator is used to check if the defined 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. You can notice that the variable exists.
Case 02: Check for String Variable by Parameter Expansion
To check if a string variable is set or not, you can adopt parameter expansion with the help of the -z
operator. It checks If a variable is set but does not give any information about the type of value the variable holds. Now write the following script to check if a string variable is set:
#!/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
a="Hello,how are you?"
holds a string. The -z "$(a+x)
operator checks if the variable length is zero or not. Now, run the script. As the variable was not empty, the above script executed the else block of the script.
Case 03: Check for Variables Using Modifiers
- Using “+set” Modifier
Using the -z
option along with the +set
modifier within the “if else” statement aids in finding variables in bash. If you don’t declare the variable in the bash script, it will return true. 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
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”.
Now, run the script.
As 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”.
- Using “-unset” Modifier
This -unset
modifier with the -z
option checks if the variable is unset and null. When you declare any variable containing no value, It returns as true. 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
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.
Now, run the script. As the variable
x
doesn’t hold any value, the “if” block executes and the output shows that the “variable x is unset”.
Method 03: Using “-n” Operator
The -n
operator in Bash is utilized to check if a variable exists by verifying whether its length is nonzero. When combined with an “if else” statement, it allows you to create conditional logic based on whether a variable has been defined or not.
Case 01: Checking for an Integer Variable is Set in Bash
Write the following script in your Bash file to check if an integer variable is set or not:
#!/bin/bash
number=10
if [ -n "$number" ]; then
echo "The variable exists."
else
echo "The variable does not exist."
fi
number
is assigned the value 10. The condition -n $number
within the “if else” statement checks whether the length of the variable ‘$number’ is nonzero (using the -n
operator). Now, run the script.
As the length of the variable number
is nonzero, the “if” block executes and the output shows that “The variable exists.”
Case 02: 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.
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
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. As the environment variable is set, the “if” block of the script runs and the output shows that the “variable is set.”
Case 03: 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
-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.
You can see that the environment variable is set in your system.
Case 04: 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 not appropriate to use 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
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.
You can see that the output shows the defined variable a exists.
Case 05: 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
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. Since the
a
variable is non-empty, the output shows that the variable is set.
Case 06: Check for Variable Using Modifiers
- Using “+set” Modifier
You can employ modifiers with the -n
option too. The +set
modifier returns the empty variable as “true”. Otherwise, the script will execute the “False” code block. Now, you can follow the steps given below:
#!/bin/bash
x=10
if [[ -n ${x+set} ]];then
echo "variable x is set"
else
echo "variable x is not set"
fi
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. After running the script, the output shows that the “variable x is set”.
- Using “-unset” Modifier
Within the “if else” statement, the -n operator with -unset modifier gives the output by checking the string length of the assigned variable. 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
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. Since I have set the Linuxsimply.com string in the bash script. Therefore, it shows ‘string is set’.
Method 04: 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
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. The output shows that the variable is set as the variable
a
defined in the script.
Summary of the Modifiers and Options
Check the following chart of the options and modifiers used above to have a better understanding:
Option | Non-empty | Empty | Not set or not declared |
---|---|---|---|
-v | True | True | False |
-z | False | True | True |
-n | True | False | False |
-z+set | False | False | True |
-z-unset | False | True | False |
-n+set | True | True | False |
-n-unset | True | False | True |
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 +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?
You can utilize this ‘${}’
sign-in parameter expansion method in bash. It allows you to manipulate variables or access specific attributes of variables.
${variable}
is used to access the value of the variable named variable.${variable:-default}
will use the value of variable if it’s set, otherwise, it will use default.${#variable}
will return the length of the value stored in variable.${variable%pattern}
will remove the shortest match of pattern from the end of variable.${variable/pattern/replacement}
will replace the first occurrence of pattern in variable with replacement.
How to read a variable in bash?
You can use the read
command to read the variable in bash. read name
will take the value entered by the user and store it in name
variable. However, this command can read multiple values at once. For example, read first_name last_name
will read two values entered by the user and store the values to first_name
and last_name
variable respectively.
Related Articles
- Check If An Input Argument Exists in Bash [4 Methods]
- Check If a String Contains Substring, Number & Letter in Bash
- Check If a String is Empty or Not in Bash [5 Methods]
- How to Compare Strings in Bash With if Statement [6 Methods]
- How to Compare Numbers in Bash With If Statement [2 Methods]
- Check If Array Contains an Element in Bash [6 Methods]
- Bash if-else Condition in One-Line [2 Ways]
- Using grep in if Statement in Bash [4 Cases]
- How to Use Regex in Bash If Condition? [4 Cases]
- Bash rm If Exists [All Case Explained]
- What is ‘$?’ in the Bash if Statement? [8 Examples]
<< Go Back to If Else in Bash | Bash Conditional Statements | Bash Scripting Tutorial