BudiBadu Logo
Samplebadu

Bash by Example: Environment Variables

Bash 5.0+

Learn the difference between local shell variables and exported environment variables with this code example, and how to access system globals.

Code

#!/bin/bash

# Define a local variable
local_var="I am local"

# Define and export an environment variable
export GLOBAL_VAR="I am global"

# Accessing standard environment variables
echo "User: $USER"
echo "Home: $HOME"
echo "Shell: $SHELL"

# Showing the difference in a child process
# We start a new bash shell to test visibility
bash -c '
  echo "Inside child shell:"
  echo "  local_var: $local_var"   # Will be empty
  echo "  GLOBAL_VAR: $GLOBAL_VAR" # Will be visible
'

Explanation

In Bash, variables can be either local to the current shell session or "exported" to the environment. Local variables are only visible within the script or shell instance where they are defined. They are not passed down to child processes (scripts or programs launched from the current shell).

Environment variables, created using the export command, are inherited by child processes. This is the primary mechanism for passing configuration (like PATH, USER, EDITOR) to programs. System-wide environment variables are typically set in startup files like .bashrc or /etc/profile.

Common environment variables include $HOME (user's home directory), $PATH (list of directories to search for executables), and $USER (current username). It is convention to name environment variables in ALL CAPS, while local variables are often lowercase.

Code Breakdown

4
local_var="..." defines a standard local variable. This variable is confined to the current shell process and is not visible to child processes.
7
export GLOBAL_VAR promotes the variable to an environment variable. Any program started by this script will receive a copy of GLOBAL_VAR.
10-12
$USER, $HOME, and $SHELL are standard system environment variables. They are automatically set by the login process or the OS.
16-20
bash -c spawns a child process. Inside this child, $local_var is empty (not inherited), but $GLOBAL_VAR is accessible (inherited).