5 Methods to Check If Environment Variable is Set in Bash Script

Bash scripting offers many tools and techniques for effective automation and control over various aspects of system management. One essential task often encountered is determining whether an environment variable is set or not. These variables hold crucial configuration information and can significantly influence the behavior of programs and scripts. In this article, I will delve into different methods to check if an environment variable is set using the Bash scripting language. So let’s start!

Key Takeaways

  • Using the if statement to check the environment variable.
  • Getting Familiar with double brackets to check if an environment variable is set.
  • Learning how to use conditional expressions in a bash script.

Free Downloads

5 Different Methods to Check if the Environment Variable is Set Using Bash Script

When working in a Linux environment, there are several methods you can employ within a bash script to determine if an environment variable is set such as Using if statement, printenv Command, env command with grep, using conditional statement, parametric expression, and so on. These methods vary from simple command-line checks to more intricate shell scripting techniques. Each approach caters to different use cases and preferences. Here I am going to describe five methods that can leverage your idea about the topic.

You can read the Comparative Analysis of Methods section to distinguish between these methods and best pick one for your need. 

Method 01: Utilizing the if Conditional Expression to Check if the Environment Variable is Set

By employing a construct like an if statement, you can check if an environment variable is set using the bash script. This mechanism facilitates customized actions based on the variable’s presence or absence. Here, I will first check whether a variable is an environment variable. If not, I will export the variable to the environment and check whether my algorithm identifies the environment variable as a set variable correctly So let’s begin.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a file in Nano:

nano if_set.sh
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • if_set.sh: Name of the file.

❸ Copy the script mentioned below:

#!/bin/bash

#Exporting a null variable
export -p var=""

#Deploying if statement to check if the var is set
if [ x"${var}" == "x" ]; then
 	echo "Value is not assigned to an environment variable"
  else
 	echo "Value is assigned to an environment variable"
  fi
EXPLANATION

The code begins by initializing the variable var as empty. Then, it employs an if statement to assess whether the variable’s value is an empty string using [ x”${var}” == “x” ]. The use of x and double quotes safeguards against potential issues when dealing with unset variables or values that include spaces or special characters.

If the comparison indicates that the variable var is empty or unset, the script prints the message “Value is not assigned to an environment variable.” Conversely, if the variable does have a value assigned to it, the script prints “Value is assigned to an environment variable.” The script concludes with the fi keyword, which marks the end of the if statement.

❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.

❺ Use the following command to make the file executable:

chmod u+x if_set.sh
EXPLANATION
  • chmod: changes the permissions of files and directories.
  • u+x: Here, u refers to the “user” or the owner of the file and +x specifies the permission being added, in this case, the “execute” permission. When u+x is added to the file permissions, it grants the user (owner) permission to execute (run) the file.
  • if_set.sh: is the file name.

❻ Run the script by the following command:

./if_set.sh

Using the if Conditional Expression to Check if the Environment Variable is Set-1As I didn’t assign any string or value in the environment variable before employing the echo command, thus the bash file returns the message depicted in the image above.

Now if you want to set an environment variable and check whether the set value exists in the environment, follow the following code by modifying the previous one. To do so copy the script mentioned below in there.

Script (ifset1.sh) >

#!/bin/bash

#Exporting var value to the environment
var="LinuxSimply"

#Deploying if statement to check if the var is set
if [ x"${var}" == "x" ]; then
 	echo "Value is not assigned to an environment variable"
  else
 	echo "Value is assigned to an environment variable"
  fi
EXPLANATION

I have made the following changes in the previous code. First, I assigned LinuxSimply as a string to the var variable and then made it an environment variable using the export command.

Now make if_set1.sh file executable by following step 5 and run the script by using the following command:

./if_set1.sh

Using the if Conditional Expression to Check if the Environment Variable is Set-2In this case, the if statement returns true as I assigned a value to the exported variable, and the output line displays Value is assigned to an environment variable.

Method 02: Implementing the Double Square Brackets

Another way to check if a variable is set or not is by using the double square bracket [[ … ]] construct in Bash. This construct provides more advanced conditional capabilities compared to the single square bracket [ … ] syntax. Here I have provided a code that shows how you can use the double square bracket to check if an environment variable is set. Let’s check this out.

You can follow the steps of method 01, to save & make the script executable.

Script (double_bracket.sh) >

# Check if the variable is set
[[ x"${ENV_VARIABLE}" == "x" ]] && echo "Value is not assigned to an environment variable" || echo "Value is assigned to an environment variable"
EXPLANATION

The Bash script checks whether the environment variable ENV_VARIABLE is set. It uses a conditional expression [[ … ]] along with a comparison to an empty string to determine if the variable is unset. If it is unset, it prints “Value is not assigned to a variable” using the echo command; otherwise, if the variable has a value, it prints “Value is assigned to a variable“. The x before ${ENV_VARIABLE} is used to avoid potential parsing issues, ensuring that even if the variable is unset, the comparison will still work as expected.

Now run the script by using the following command

./double_bracket.sh

Using the Double Square Brackets-1As the exported variable doesn’t contain any value in it, it returns “Value is not assigned to an environment variable” in the command line.

Now if you want to set an environment variable and check whether the set value exists in the environment, follow the following code by modifying the previous one. To do so copy the script mentioned below in there.

Script (double_bracket1.sh) >

#!/bin/bash

# Define an example environment variable
export -p ENV_VARIABLE="LinuxSimply"

# Check if the variable is set
[[ x"${ENV_VARIABLE}" == "x" ]] && echo "Value is not assigned to an environment variable" || echo "Value is assigned to an environment variable"
EXPLANATION

In this Bash script, an environment variable named ENV_VARIABLE is defined using the export command with the value “LinuxSimply“. Then, a conditional expression [[ … ]] is used to check whether the environment variable is set. If the variable is set, the script will output “Value is assigned to an environment variable“; if the variable is unset or has an empty value, it will output “Value is not assigned to an environment variable“. The x before ${ENV_VARIABLE} is used to prevent parsing issues, ensuring accurate comparison even if the variable is unset or empty.

Run the code using the following command.

./double_bracket1.sh

./double_bracket1.shAs the ENV_VARIABLE is now got LinuxSimply as a value, the command line displays Value is assigned to an environment variable.

Method 03: Using the Parameter Expression to Check Whether the Environment Variable Exists

Following the previous method, you can use Bash’s builtin parameter expression to easily check if an environment variable is set or not. This expression provides convenient ways to determine variable status within your scripts. Follow the code I am going to describe below.

You can follow the steps of method 01, to save & make the script executable.

Script (para_expression.sh) >

#!/bin/bash

#exporting the VAR variable to the environment
export -p VAR="LinuxSimply"

#employing parameter expression to check if the variable is set or not
[[ ${VAR:-"unset"} == "unset" ]] && echo "Value is not assigned to the variable" || echo "Value is assigned to a variable and the value is $VAR"
EXPLANATION

This Bash script starts by exporting the variable VAR with the value “LinuxSimply” into the environment. It then employs a parameter expansion technique to determine if the variable is set or not. The [[ ${VAR:-“unset”} == “unset” ]] expression checks if the variable is unset or has no value assigned and if true, it prints a message stating that the value is not assigned to the variable. If false, indicating that the variable has a value, it prints a message indicating that the value is assigned to the variable and displays the actual value using the $VAR reference with the echo command.

Now run the code by using the following command.

./para_expression.sh

Using the Parameter ExpressionAs the VAR variable contains LinuxSimply within it, the echo command returns “Value is assigned to a variable and the value is LinuxSimply”.

Method 04: Using the Conditional Expressions to Check if Environment Variable is Set

Along with the if statement, we can also incorporate various options such -z flag, -n flag, -v option, and so on to check whether the environment variable is set or not by using a bash script.  Down below, I have provided three different cases to describe their functionality in this regard. Check it out and don’t stop to grow more.

Case 01: Utilizing the -z Option to Check if Environment Variable is Set

In Bash, you have a handy trick: the -z condition. This conditional statement returns true when a string is empty. With this, you can easily see if a variable is set or not.

You can follow the steps of method 01, to save & make the script executable.

Script (z_expression.sh) >

#!/bin/bash

# Define and export environment variables
export -p var1=""
export -p var2="Hello, world!"

# Check if variables are set using -z
if [ -z "$var1" ]; then
	echo "var1 is not set"
else
	echo "var1 is set"
fi

if [ -z "$var2" ]; then
	echo "var2 is not set"
else
	echo "var2 is set"
fi
EXPLANATION

In this Bash script, two environment variables, var1, and var2, are defined and exported. The script then uses the -z test to check if each variable is empty or unset and then displays an output line with the help of an echo command. The first conditional statement checks if var1 is empty, and if true, it outputs that var1 is not set. Conversely, if var1 has a value, it outputs that var1 is set. The second conditional statement applies the same logic to var2, indicating whether it is set or not based on whether it is empty.

Now run the code by using the following command.

./z_expression.sh

Using the -z Option to Check if Environment Variable is SetAs the first variable var1 doesn’t contain value but var2 does, the script gives var1 is not set and var2 is set in the command line.

Case 02: Using the -n Option to Check if Environment Variable is Set

Unlike the –z option, the -n option returns the output as true if the test variable is not an empty string. So the algorithm has to be changed accordingly to utilize the option effectively.

You can follow the steps of method 01, to save & make the script executable.

Script (n-expression.sh) >

#!/bin/bash

# Define the name of the environment variable to check
Var1=""
Var2="LinuxSimply"

# Check if the environment variable is set using -n
if [ -n "${Var1}" ]; then
	echo "Var1 is set"
else
	echo "Var1 is not set"
fi

if [ -n "${Var2}" ]; then
	echo "Var2 is set"
else
	echo "Var2 is not set"
fi 
EXPLANATION

This Bash script initializes two variables, Var1 and Var2, with values ” ” and “LinuxSimply” respectively. It then employs the -n test to determine if each variable is set or not. The first conditional statement checks if Var1 is not empty and if true, it outputs “Var1 is set.” Conversely, if Var1 is empty, it outputs “Var1 is not set.” The second conditional statement follows the same logic for Var2, indicating whether it is set or not based on whether it’s empty or not.

Now run the code by using the following command.

./n-expression.sh

Using the -n Option to Check if Environment Variable is SetHere the output “Var1 is not set” and “Var2 is set“ both reflect the status of the two environment variables based on the -n flag, indicating whether they are set or not.

Case 03: Using the -v Option to Check if Environment Variable is Set

Following the previous case, option -v helps us see if an environment variable is set or not using the bash script. You can use the following syntax to check:

[ -v variable_name ]

You can use this syntax in if statements when needed. However, the -v option basically says if a variable given to it has been declared before or not, irrespective of whether it contains any value or not. Down below there is a script demonstrating how the -v option can be used to determine whether variables are initialized or not.

You can follow the steps of method 01, to save & make the script executable.

Script (v-expression.sh) >

#!/bin/bash

# Declare and initialize variables
initialized_var="I have a value"
empty_var=""

# Check if variables are set using -v option
if [ -v initialized_var ]; then
    echo "initialized_var is set and has a value."
else
    echo "initialized_var is not set."
fi

if [ -v empty_var ]; then
    echo "empty_var is set but has no value."
else
    echo "empty_var is not set."
fi
EXPLANATION

The script begins by declaring two variables: initialized_var and empty_var. The first variable is given a value, while the second variable remains empty. Then, the script uses conditional statements (if-else) to check the status of these variables using [ -v variable_name ]. For initialized_var, the script checks if it is set by evaluating [ -v initialized_var ].

Since this variable has been assigned a value, the condition evaluates to true, leading to the execution of the first echo statement, which states that initialized_var is set and has a value. On the other hand, for empty_var, the script checks its status with [ -v empty_var ]. Although this variable is declared, it doesn’t have any value assigned to it. As a result, the condition evaluates to true, and the script executes the second echo statement, indicating that empty_var is set but has no value.

Now run the script by using the following command.

./v-expression.sh

Using the -v Option to Check if Environment Variable is SetAs the initialized_var contains a value in it but empty_var doesn’t, the command line return “initialized_var is set and has a value” and “empty_var is set but has no value” upon execution of the script.

Method 05: Utilizing the test Command with the -n Conditional Expression

You can also employ the test command with the –n conditional expression to check if the environment variable is set or not using bash. This also allows you to determine whether a specific environment variable has been assigned a value or remains unset.

You can follow the steps of method 01, to save & make the script executable.

Script (var_with_test.sh) >

#!/bin/bash

#Checking whether ENV_VARIABLE is set or not  
if test -n "$ENV_VARIABLE"; then
    echo "ENV_VARIABLE is set"
else
    echo "ENV_VARIABLE is not set"
fi
EXPLANATION

In this Bash script, the presence of the environment variable ENV_VARIABLE is checked using the test command with the -n option. If the variable is not empty (i.e., it’s set), the script outputs “ENV_VARIABLE is set.” Conversely, if the variable is empty or not set, it outputs “ENV_VARIABLE is not set.

Now run the script by using the following command.

./var_with_test.sh

Using the test Command with the -n Conditional ExpressionAs the image depicts above, The command line returns ENV_VARIABLE is not set since I did not create and export ENV_VARIABLE variable initially.

Comparative Analysis of the Methods

Here’s a comparative analysis of different methods to check if an environment variable is set in a Bash script:

Methods Pros Cons
Method 1
  • Simple and widely understood syntax.
  • Portable across various shell environments.
  • Requires proper quoting for variables with spaces.
  •  Comparatively verbose syntax.
Method 2
  • Well-suited for basic scripts and quick checks.
  • Better handling of complex conditions.
  • Not as portable as single brackets ([ vs [[).
  •  Still requires some quoting in certain cases.
Method 3
  • Concise, singleline expression.
  • Useful for simple output based on variable presence.
  • Limited to indicating if set, not custom messages.
  • Less intuitive for more complex conditions.
Method 4
  • No need to branch the code.
  • Directly captures presence or absence.
  •  May not be as intuitive for those unfamiliar with Bash.
  •  No option to customize messages.
Method 5
  • Well-suited for concise scripts and one-liners.
  • Works in various shell environments.
  • Syntax may seem less intuitive compared to brackets.
  • Slightly more verbose syntax.

Among the methods mentioned for checking if an environment variable is set, Method 2 stands out as the most preferable choice. This approach offers a balance of readability, parameter expansion safety, and ease of use. It eliminates the need for explicit quoting of the variable and handles spaces and special characters within the variable more reliably. Moreover, the logical operators supported by [[ … ]] enable the creation of complex conditions if necessary.

In contrast, the Method 5 conditional expression requires explicit quoting and parameter expansion handling, potentially introducing complexity. While Method 3 and Method 4 have their use cases, Method 2 offers a clearer, more intuitive syntax for checking variable existence,

Conclusion

In conclusion, checking whether the environment variable is set or not in bash is an important thing. A coder should be aware of this before assigning the value to any of the scripts further. Here in this article, I have demonstrated five different methods to check if the environment variable is set or not. However, if you have any confusion or suggestions regarding this article, don’t forget to comment below. I am one step away to discuss with you. Thank you!

People Also Ask

What is Setenv in Linux?
The setenv() function includes the variable name and its value in the environment if the name isn’t already present. In case the name is already present, the value associated with it can be updated to the new value if the overwrite condition is met. When overwrite is set to zero, the value of the existing name remains unchanged. The function creates duplicates of the strings indicated by name and value.
Where is Setenv located?
setenv is typically available in programming environments and libraries, such as C libraries, rather than being a standalone command or utility in most Unix-like systems, including Linux. It manipulates environment variables.
What does env do in bash?
In bash, the env command executes a command within a modified environment. It also allows you to set or override environment variables for that specific command’s execution.
How do I check if a variable is assigned in Bash?
In Bash, you can check if a variable is assigned using the -v option with the test command or its equivalent, [ ] brackets, like this: [ -v variable_name ]
Rate this post
Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment