How to Export Environment Variables With Bash? [4 Examples]

In Bash scripting, environment variables play a crucial role in sharing data across different parts of a script and enabling seamless communication between the script and its subprocesses. Understanding how to export environment variables is essential to be proficient in Bash scripting. In this article, I will demonstrate how to set or export environment variables with Bash. So let’s Start!

Key Takeaways

  • Getting a comprehensive idea of exporting Bash variable.
  • Getting familiar with exporting bash variables through the command line.
  • Exporting function to the environment.

Free Downloads

What Does the “export” Command Do to a Bash Variable?

A Bash variable makes its value available to other processes and subshells in the current environment by using the export command in the Bash shell. When a variable is exported, the variable is considered to be set and its value can be accessed by other scripts, programs, and child processes spawned from the current shell session.

Moreover, it allows for sharing of data between different parts of a script and enables communication between the parent shell and its subprocesses. However, they won’t be available in the parent shell where you ran the script from. If you want to set environment variables permanently for your user session, you can consider adding them to your shell’s profile configuration files (e.g., ~/.bashrc or ~/.bash_profile).

4 Practical Examples of Setting Variables in Bash Scripts Using “export” Command

Here, I have demonstrated 4 different examples related to the setting of variables in Bash using the export command. Carefully review all of the examples and don’t forget to exercise it in your distribution.

Example 01: Setting Variables Through Command Line

Exporting variables through the command line is a convenient and powerful way to make data accessible to various processes and programs in a Unixlike environment. In the command line, you can swiftly set and export environment variables using a single command which is far easier than calling the environment variable through the Bash script. Here, I am going to illustrate the process using the command line image for your perusal.

Steps to Follow >

➊ Firstly, export the project_name variable containing a string LinuxSimply.

➋ Then, call the env command to verify if the new variable is assigned or not.exporting bash variableAs the image depicts below, project_name with its value has been successfully assigned as an environment variable. checking exported bash variable➌ Now to access and display the value, use the following command in the terminal.

echo $project_name

display exported variable using echo command As the image suggests, the project_name variable returns its environment value LinuxSimply in the command line.

Example 02: Using Exported Environment Variables in Shell Scripts

In example 01, I stored LinuxSimply in the project_name variable and then exported it as an environment variable. Now in this second example, I am going to call the project_name variable using the bash script file. So, let’s jump onto this!

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

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

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

❸ Copy the script mentioned below:

#!/bin/bash

#calling the environment variable project_name of example 01
echo "The name of the project is $project_name"
EXPLANATION

The first line #!/bin/bash specifies the interpreter to use (/bin/bash) for executing the script. As the project_name variable is already stored as an environment variable from Example 1, we simply call the project_name variable with the echo command to display its value in the command line.

❹ 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 export_env._var.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) of the file permission to execute (run) the file.
  • export_env_var.sh: is the name of the file

❻ Run the script by the following command:

./export_env._var.sh

execute the file to print the exported variableUpon executing the bash file, it returns the environment variable LinuxSimply variable and displays “The name of the project is LinuxSimply” to the command line.

Example 03: Setting a Function Using “export” Command in Bash Script

Exporting and executing functions using bash script allows you to make these functions available to other processes or subshells. It also enables you to reuse them across multiple scripts or sessions. To export a function, you need to use the export command followed by the function definition. Down below a demo function has been depicted to provide you an idea about it. Follow the steps and execute it in your terminal.

You can follow the steps of Example 02, to save & make the script executable.

Script (exporting_function.sh) >

#!/bin/bash

#defining the function and storing it
func() { echo “This is a demo function”;}

#Set the temporary environment function using the export command
export -f func 

#calling the function to display it in the command line
func
EXPLANATION

This Bash script starts by defining a function named func() and stores the string “This is a demo function” within it. Next, the defined function is channeled to the environment using the export command. Finally, the func is called at the later part of the code to display it in the command line.

After making the file executable for the current user, run the following command to the command line to execute the bash file.

./exporting_function.sh

Exporting a Function with Bash Script

Here the prompt returns the function value “This is a demo function” which i stored as an environment value earlier.

Example 04: Set Environment Variable and Print the Value Using the “printenv” Command in a Bash Script

Till now you have seen different examples such as exporting variables and exporting functions using a Bash Script. Now I will show you how you can export variables using the export command and print the value using printenv command in a bash script. Follow the steps described below.

You can follow the steps of Example 02, to save & make the script executable.

Script (export_printenv.sh) >

#!/bin/bash

#defining of the x variable 
x=10 

#exporting the variable to the environment
export x

#printing the environment variable
printenv x

EXPLANATION

The Bash script initializes a variable named x with the value 10. It then exports this variable to the environment, allowing other processes to access it. Subsequently, the script uses the printenv command to display the value of the environment variable x, which in this case will output 10.

After making the file executable for the current user, run the following command to the command line to execute the bash file. 

./export_printenv.sh

Export Variable and Print the Value Using the printenv CommandAs the image shows, upon execution of the export_printenv.sh file, the x variable returns 10.

Assignment Task

  1. Write a Bash script that performs the following tasks:
    • Create two environment variables: NAME and AGE.
    • Assign your name to the NAME variable and your age to the “AGE” variable.
    • Export both bash variables so that they are available to subprocesses.
    • Create a second script called display_info.sh.
    • In display_info.sh., use the printenv command to display the values of NAME and AGE on the screen.
    • Run display_info.sh.and verify that it correctly shows your name and age.
  2. Write a Bash script that exports an environment variable based on a condition. Perform the following tasks:
    • Define a variable called SPECIAL_DAY and assign it the value Sunday.
    • Check if the day of the week is Sunday using the date command or any other method you prefer.
    • If it is Sunday, export an environment variable called IS_SPECIAL_DAY and set it to true.
    • Create another script called check_special_day.sh.
    • In check_special_day.sh, use the printenv command to check if IS_SPECIAL_DAY is set and display a corresponding message.

Conclusion

In conclusion, exporting or setting environment variables in Bash is a powerful feature that allows you to make the variables accessible to other processes and scripts. In this article, I have given you an overall demonstration of how you can export environment variables with 4 examples. However, if you have any questions or queries related to this article, feel free to comment below. I will get back to you once you comment. Till then, Thank you.

People Also Ask

How to export env in shell script?
To export an environment variable in a shell script, use the export command followed by the variable name and its value. eg. export MY_VARIABLE=”Hello, World!”. This makes the variable MY_VARIABLE available to other processes and subshells launched from the current shell session.

How to access environment variables in command line?
To access environment variables in the command line, use the variable name preceded by the $ symbol. For eample, echo $MY_VARIABLE. Here, it will print the value of the environment variable named MY_VARIABLE.

How to check if environment variable is set in bash script?
To check if an environment variable is set in a bash script, you can use the -v or ! -z test operators. The operator evaluates to true if the variable is set (i.e., it has a non-empty value) and false if the variable is not set or is empty.
Why export bash variables?
By exporting a variable, it becomes part of the environment, allowing other processes and subshells to access its value. This is useful when you want to share data between different parts of a script or when you want external programs or child processes to have access to certain variables set in the parent shell.

Related Articles


<< Go Back to Variable Declaration and Assignment | Bash Variables | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
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