How to Print Env Variable Linux [5 Best Methods]

Written by

Reviewed by

Last updated: June 6, 2024

Expert verified

SVG Image

TL;DR

To print env variable Linux, you can try these methods:

  1. Use printenv to display all environment variables or printenv -u VARIABLE_NAME for a specific variable.
  2. Type env to list all environment variables or env VAR=value command to run a command with custom environment settings.
  3. Use echo $VARIABLE_NAME to print the value of a specific environment variable.

Read the guide below to learn different methods to print env variables Linux and common errors that can occur and the possible solutions.

Have you ever had trouble getting your programs to find the right files or configurations? Environment variables can solve this problem by storing critical information that your computer uses to manage applications and scripts. In this post, I’ll show you how to print environment variable Linux using commands like printenv, env, echo, and declare. You’ll also learn some best practices for managing these variables. By the end of this guide, you’ll have the skills to efficiently manage your system’s environment variables and troubleshoot any related issues confidently.

What are Environment Variables?

Environment variables are like small notes you leave for your computer to tell it how to behave. They store information that different programs and scripts can use. For example, they can tell your computer where to find certain files or how to display text.

Environment variables are important because they:

  • Help programs find files: By setting variables like PATH, you can tell your computer where to look for programs you want to run.
  • Customize your environment: You can set variables to change the behavior of your system and applications without modifying the code.
  • Improve efficiency: Instead of setting the same configuration repeatedly, you can use environment variables to set them once and apply them everywhere.
  • Ensure consistency: They provide a consistent way to manage settings across different programs and scripts.

How to Print Env Variable Linux

To print env variable Linux, you can use several commands. The simplest way is to use the echo command: echo $VARIABLE_NAME. This will display the value of the specified variable. For a comprehensive list of all environment variables, you can use the printenv.

Alternatively, you can use the env command by typing env to see all variables or env VAR=value command to run a command with a custom environment setting. These commands help you quickly and efficiently manage your environment variables.

Keep reading for the detailed steps for five different methods to print environment variables:

1.  printenv Command

The printenv command is a simple yet powerful tool to print environment variables in Linux. It provides a quick overview of all variables, aiding efficient system inspection and troubleshooting. Follow these steps:

  1. Open your Terminal window.
opening terminal 37
  1. To Linux print all environment variables, type:
printenv
  1. This will provide a comprehensive list of all environment variables set in your Linux system.
printing all available environment variables using printenv
  1. If you need to print specific variables, use the -u flag followed by the variable name, like this:
printenv -u PATH
  1. This command will display the value of the PATH variable, or any other variable you specify after the -u flag.
printing specific variable using printenv

2. env Command

The env command is similar to printenv but excels in executing commands with custom environments. It allows for a more dynamic approach to setting variables while running specific commands, making it a preferred choice for developers. Here is the step-by-step guide:

  1. To display all environment variables using env, open the Terminal and type:
env
  1. This will show a list of all environment variables set in your system.
printing all available variables using env command
  1. You can also use env to run commands with custom environment settings:
env VAR=value command

Replace VAR with the variable name, value with the desired value, and command with the actual command you want to execute.

customizing environment variable
  1. By default, the script will print Hello if the GREETING environment variable is not set.
original value of variable

3. echo Command

The echo command is a built-in shell command that enables quick display of specific variables. Ideal for debugging and script development, it offers a straightforward method to view single variables at a glance. Follow these steps:

  1. To print a specific variable, use $ followed by the variable name, like this:
echo $PATH
  1. This command will display the value of the PATH variable, or any other variable you specify after the $ symbol.
printing variable using echo command

4. declare Command

The declare command offers advanced control over variable properties, making it invaluable for managing complex variables and their attributes. Here is how to do it:

  1. To display all environment variables using declare, open the Terminal and type:
declare
  1. This will show a list of all environment variables along with their attributes.
printing variables using declare command
  1. You can use various options with declare to customize variable behavior:
  • Use -p to display variable attributes, showing additional information about each variable.
  • Use -x to mark variables for export, making them available to child processes.
  • Use -g to create global variables, which are accessible across different shell sessions.

5. Scripting to Print Variables

Scripting empowers advanced users to automate variable display and manipulate output formats. Ideal for customizing variable extraction in complex scenarios. Follow these steps:

  1. Create a Bash script to display variables. For instance, a Bash script to print all variables would look like this:
#!/bin/bash
printenv
  1. Save the above script in a file with a .sh extension, such as variables.sh.
  2. To execute the script, navigate to its location in the Terminal and run the following command:
./variables.sh
  1. This will execute the script and display all environment variables in your Linux system.
printing all available variables using script file

How to Create Environment Variables on Linux

Creating environment variables in Linux is a fundamental task that allows you to set up custom variables to store configuration settings, paths, and other data that different applications and scripts can use. This is particularly useful for setting up development environments, specifying configuration options, and managing system behavior dynamically.

  1. Press Ctrl + Alt + T to open the terminal.
  2. Type the following command to create a temporary environment variable:
export MY_VAR="my_value"

This command sets MY_VAR to “my_value” for the current terminal session. It will not persist after you close the terminal.

creating a temporary environmental variable
  1. To verify the environment variable, run:
echo $MY_VAR
  1. Press Enter.
verifying that the variable has been created
  1. Open the ~/.bashrc file in a text editor (e.g., nano):
nano ~/.bashrc
opening bashrc file in nano editor
  1. Add the following line at the end of the file:
export MY_VAR="my_value"
adding environmental variable in bashrc file to use it permanently 1
  1. Save and close the file (for nano, press Ctrl + X, then Y, and Enter).
saving and exiting the bashrc file
  1. To apply the changes, type:
source ~/.bashrc

This command reloads the .bashrc file, applying the new environment variable for all future terminal sessions.

applying the changes

How to Delete Environment Variables on Linux

Deleting environment variables in Linux is necessary when a variable is no longer needed or if it contains sensitive information that should not persist. Properly removing unused environment variables helps maintain a clean and secure system environment.

  1. Open Terminal. Type the following command to unset (delete) a temporary environment variable:
unset MY_VAR

This command removes MY_VAR from the current terminal session.

deleting the temporary environmental variable
  1. To verify that the environment variable has been deleted, type:
echo $MY_VAR

No output (blank line), indicating that MY_VAR is no longer set.

verifying that the variable has been deleted
  1. Open the ~/.bashrc file in a text editor (e.g., nano):
nano ~/.bashrc
opening bashrc file in nano editor 1
  1. Locate the line that sets the environment variable. Delete or comment out this line (by adding # at the beginning):
#export MY_VAR="my_value"
deleting the environmental variable from bashrc file
  1. Save and close the file (for nano, press Ctrl + X, then Y, and Enter).
saving and exiting the bashrc file after deleting
  1. To apply the changes, type:
source ~/.bashrc

This command reloads the .bashrc file, ensuring that the environment variable is no longer set in future terminal sessions.

applying the changes 1

5 Best Practices to Print Environment Variables in Linux

Printing environment variables in Linux is critical for system administrators and developers. Adopting best practices will empower you to confidently navigate the world of environment variables in Linux. Efficiently print and manage variables, troubleshoot issues, and optimize your system for peak performance. Here are five best practices to master this essential skill:

  • 🔍 Use printenv for Quick Overview: The printenv command displays all environment variables at once, providing a quick overview of system configurations. It’s popular for its efficiency and simple syntax, allowing rapid information retrieval directly from the Terminal.
  • 📝 Document Customized Variables Properly: Keep detailed documentation of customized environment variables, including their purposes and side effects. Proper documentation helps track changes, aids understanding, and simplifies sharing and collaboration.
  • Use echo for Specific Variables: To print a specific variable’s value, use echo followed by the variable name (e.g., echo $VARIABLE). Be cautious with special characters in variable values to avoid output issues.
  • 🖥️ Leverage GUI Tools for User-Friendly Exploration: GUI tools like System Monitor provide an intuitive interface to visualize and monitor environment variables. These tools are especially useful for beginners and desktop users, enhancing their Linux experience.
  • 🧰 Consider External Tools for Advanced Control: External tools like env-var or dotenv offer advanced features such as variable manipulation, encryption, and integration with other tools. They are beneficial for complex systems requiring granular control over environment variables, boosting productivity and workflow.

Linux Print Env Variable: Wrapping Up

In this article, I have explored various methods to Linux print environment variables using commands like printenv, env, echo, and declare, along with scripting techniques.

For further reading, I recommend:

  • Checking out how to prettify JSON in the command line, which can improve your data management and visualization skills.
  • Exploring ways to use the grep OR,AND, and NOT condition to search for specific environment variable values within files and outputs.
  • Understanding how to use the read command in Linux for better user input handling in your scripts.

Frequently Asked Questions

How do I set a new environment variable in Linux?

To set a new environment variable in Linux, you can use the export command followed by the variable name and its desired value. For instance, to create a variable named MY_VARIABLE with the value value, use the following command: export MY_VARIABLE=value. This will make the variable accessible to the current shell session and any child processes launched from it. If you want to make the variable available in every new shell session, consider adding the export command to the ~/.bashrc or ~/.bash_profile file.

Is there a limit to the number of environment variables that can be set in Linux?

Yes, there is a limit to the number of environment variables that can be set in Linux. The available system resources, including memory and processing power determine the maximum limit. While this limit is generally quite high, it is crucial to be mindful of resource usage, especially in environments with limited capabilities. Overloading the system with excessive variables can lead to performance degradation or even system instability. Therefore, it’s essential to carefully manage and optimize the number of environment variables based on the specific requirements of your Linux system.

Can I permanently print specific variables on system startup?

Absolutely! You can ensure that specific environment variables are permanently available on system startup by adding them to the ~/.bashrc or ~/.bash_profile file. These files are executed every time a new shell session starts, guaranteeing that the defined variables become readily accessible in every session. Using the export command within these files allows you to set the variables’ values, making them available to all subsequent processes initiated during system startup.

Is it possible to export environment variables across different user sessions?

Indeed, exporting environment variables across different user sessions is achievable by adding the variables to the system-wide /etc/environment file. This file holds environment variable declarations that apply to all users on the system, regardless of their individual shell sessions. By appending the desired variables to this file using the export command, you ensure that they are available universally, bridging the gap between various user sessions and offering consistent configurations throughout the system.

Is it possible to restrict certain environment variables from being inherited by child processes?

Absolutely! You can restrict specific environment variables from being inherited by child processes in Linux. This capability enhances data security and isolation, preventing sensitive information from inadvertently leaking to child processes. One way to achieve this is by using the unset command to remove specific variables from the environment before launching a new process. Additionally, when starting a new process, you can explicitly specify the variables to exclude, ensuring that only necessary and non-sensitive variables are passed to the child process. By implementing these measures, you maintain finer control over the flow of data and protect your system from potential vulnerabilities.

Ojash

Author

Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

Akshat

Reviewer

Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, he’s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

Share this article
Shareable URL
Prev Post

How to Update Debian Linux [4 Effective Methods]

Next Post

How to Apt Remove Package Using Apt Package Manager[2 Proven Methods]

Leave a Reply

Your email address will not be published. Required fields are marked *

Read next