5 Methods to Check If Environment Variable is Set in Bash

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

To check if an environment variable is set in Bash, you can use the following methods:

  1. Using the “if” Conditional Expression: if else statement with [ x"${var}" == "x" ] syntax
  2. Using Double Square Brackets: [[ x"${var}" == "x" ]] syntax with AND Operator
  3. Using Parameter Expression: [[ ${var:-"unset"} == "unset" ]] Syntax with OR Operator
  4. Using Conditional Expressions: if else statement with [ -z "$var1" ]  or [ -n "${var1}" ] syntax
  5. Utilizing “test” Command With “-n” Conditional Expression

Here, don’t forget to replace the var with the environment variable you want to check. Further, the output of the condition depends on the method you are using. The following section of this article will describe each of these methods with examples. So let’s begin

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

An environment variable is a dynamic-named value that influences software behavior by storing configuration settings and system information. In Unix-like systems, they’re set in the shell, inherited by processes, and commonly used for settings like PATH and HOME.

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 with -z or -n options, printenv command, env command with grep, 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. 

1. Using the “if” Conditional Expression

To check if an environment variable is set in bash, you can employ a construct like an if conditional statement. 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. Here’s the bash script for this:

#!/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.

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:

#!/bin/bash

#Exporting var value to the environment
export -p 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

Here, I have made some changes to 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.

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.

2. Using 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.

#!/bin/bash

# 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.

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:

#!/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”.

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

3. Using Parameter Expression

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

#!/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.

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”.

4. Using Conditional Expressions

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.

Using the [ -z "$var1" ] syntax within the if condition checks whether the var1 is empty. Here’s the entire bash script:

#!/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.

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. Here’s how:

#!/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.

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 “-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 [ -v variable_name ] 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:

#!/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.

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.

5. Utilizing “test” Command With “-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. Here’s the bash script for this:

#!/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.

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 to Check If Environment Variable is Set

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

How do you check if a variable is assigned in Bash?

To check if a variable is assigned in bash, use the -v option with the test command or its equivalent, [ ] brackets, like this: [ -v variable_name ]. Here’s an example:

#!/bin/bash

if [[ -v my_variable ]]; then
  echo "my_variable is assigned."
else
  echo "my_variable is not assigned."
fi

In this example, replace my_variable with the name of the environment variable you want to check.

How to check all environment variables in Bash?

To check all environment variables in Bash, you can simply type env in the terminal and execute the command. Thus, you will receive a list of all environment variables, each accompanied by its respective value. Another method involves using the set command, which not only displays environment variables but also provides information on other shell variables.

How to check if env is set in zsh?

In Zsh, you can check if an environment variable is set using the [[ -n … ]] or [[ -z … ]] test constructs, similar to Bash. Here’s an example:

if [[ -n $VAR_NAME ]]; then
    echo "The variable is set and its value is: $VAR_NAME"
else
    echo "The variable is not set"
fi

Replace VAR_NAME with the name of the environmental variable you want to check.

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 the 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 to check if environment variable is not empty in bash?

To check if an environment variable is not empty in Bash, you can use the -n option inside the if conditional statement. Here’s the basic syntax:  if [ -n "$ENV_VARIABLE" ]. It checks if the environment variable is non-zero.

How to check environment variable with bash if ‘-z’ option?

The -z option inside the bash if statement checks if the environment variable is empty. Here’s the basic syntax: if [ -z "$MY_VARIABLE" ]. You can replace the MY_VARIABLE with the name of the environment variable you want to check.


Related Articles


<< Go Back to Using Variables in Bash Scripting | Bash Variables | Bash Scripting Tutorial

5/5 - (6 votes)
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