Environment variables are dynamic values stored inside Linux systems that are utilized by programs running in terminals or subshells. They essentially store configuration data that affects system behavior. As a developer, having a proper understanding of environment variables is crucial for writing effective bash scripts.

In this comprehensive guide, we will dive deep into environment variables – how they work, why they are important, and various methods developers can use to print and access them in Linux and Ubuntu.

What are Environment Variables?

Environment variables are name-value pairs that are available system-wide to all executed processes and sub-processes. Some common examples include:

  • $HOME – Path to the user‘s home directory
  • $PATH – Directories to search for executable programs
  • $LANG – System language and encoding
  • $TERM – Terminal emulator being used

Environment variables control several aspects of system operation and program execution:

  • Customize Shell Behavior: Variables like $HISTSIZE (command history size) and $PS1 (shell prompt) customize shell behavior
  • Store Configuration Data: Data like application settings, server ports, credentials can be stored
  • Affect Program Execution: Variables determine available resources, search paths, system locales etc. which influence how programs perform

In essence, environment variables act as customizable parameters that change system and program functions.

How Do Environment Variables Work?

Environment variables work very similarly to regular variables in programming languages. But unlike normal variables, they are inherited across child processes and exist outside the current shell instance.

The names of environment variables are case-sensitive and should be capitalized by convention e.g. $PATH.

Environment variables are initialized just like regular bash variables:

KEY=value 
KEY=value1:value2

The colon (:) allows setting multiple values for a variable.

The set builtin command can view and set variable values:

set # displays all variables
set KEY=value # sets KEY to value

set command output showing variables

Now let‘s explore the various ways environment variables can be printed and accessed in Linux.

Why Print Environment Variables?

There are several reasons developers and system administrators print environment variables during troubleshooting and script development:

  • Debug Issues: Many system, network, and program issues can be caused by environment variables being incorrectly set
  • Script Testing: While writing bash scripts, printing variables helps properly test and debug the logic
  • Understand System State: Viewing certain variables gives insights into current system configuration – paths being used, locale set etc.
  • Document Current Settings: Printing all current environment variables allows documenting the exact state, which is useful when replicating issues.

Let‘s now dive into the different techniques of printing environment variables using bash commands.

Print Using the env Command

The simplest way to print variables is using the env command without any arguments:

env

This displays all environment variables active in the current shell instance:

env command output

You can also pass the -i option to env to clear existing variables and simulate a fresh environment:

env -i  

This helps in testing scripts designed for bare environments.

Print All Variables with printenv

The most common method developers use to print variables is the printenv command:

printenv

The output contains all current variables along with those set earlier in the shell session:

printenv output

According to Linux manual pages, printenv displays the environment as name-value pairs sorted by name. Several standard variables like $HOME, $PATH, $LANG etc. get printed.

The output can be long, so it can be piped to less or more for improved readability:

printenv | less
printenv | more 

printenv piped to more

To store the variable output, it can be redirected to a file:

printenv > environment.txt  

The saved file contains all active environment variables. This is useful for documenting system state.

Print Specific Variables with grep

Instead of printing all variables, grep can be used along with printenv to display specific ones:

printenv | grep HOME

This prints only the HOME variable‘s value:

grepping home variable

Likewise, you can check for any variable names:

printenv | grep MYVAR

If it doesn‘t exist, grep prints nothing.

Print All Variables with declare

Bash also contains a declare builtin that displays variables and their values:

declare -p

declare -p output

This prints all variables – both environment variables as well as other bash variables like aliases and shell functions.

To exclusively print environment variables, use:

declare -xp 

declare -xp output

So declare -xp offers an alternative to print only environment variables.

Access Variables from /proc Filesystem

The /proc pseudo-filesystem in Linux exposes information about running processes. It contains an environ file that stores the environment variables per process:

/proc/<PID>/environ 

For example, here is how to access environment variables of the current bash process:

cat /proc/$$/environ

cat /proc/$$/environ output

The special $$ variable returns the PID of the current bash process. This allows a process to programmatically print its own environment variables.

Using /proc is useful for debugging issues in daemon and server processes by examining their environment.

Print Specific Variables with echo

A simple method to print certain environment variables is using the echo command:

echo $HOME
echo $PATH

This prints their values directly. Multiple variables can be printed together like:

echo "$USER $HOME $PWD"

If a variable doesn‘t exist, a blank string is printed.

Count All Environment Variables

To get a count of total environment variables in the current shell, use printenv with wc -l:

printenv | wc -l

This prints the number of variables along with the names:

environment variable count

The count can vary across different systems depending on active services.

A similar technique with /proc prints variables per process:

cat /proc/$$/environ | wc -l

Common Environment Variables

Some environment variables that are commonly used in Linux include:

Variable Description
$HOME User home directory path
$PATH Directories containing executable programs
$PWD Current working directory
$SHELL Current shell program
$LANG System language and encoding

Developers can leverage these standard variables for their scripts to get config data, set search paths etc.

Several other dynamic variables exist that reflect current system state like:

  • $?: Exit status of last command
  • $!: PID of last background process
  • $UID: Numeric user ID of current user

These provide useful programmatic insights.

Modifying and Adding Variables

Along with printing, developers can also modify and add environment variables.

Existing variables can be modified from the command line:

export VARNAME=newvalue

This updates the value of VARNAME globally.

Adding a new variable is also very similar:

export NEWVAR=value

This will define NEWVAR and make it available system-wide.

Modifying certain variables like $PATH affects overall system operation. Hence as a best practice, create custom variables instead of changing defaults.

Conclusion

In this comprehensive article, we explored what environment variables are, why they are important, and different techniques developers can use to access, print and modify them in Linux.

Key points include:

  • Environment variables customize shell and system behavior
  • printenv, env, declare print all active variables
  • /proc filesystem provides per-process environment data
  • Variables like $HOME and $PATH are widely used in scripts
  • Exporting variables makes them available system-wide

I hope this guide gives you a deep insight into managing essential environment variables programmatically using bash! Let me know if you have any other questions.

Similar Posts

Leave a Reply

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