Skip to main content
An environment variable in Bash is a named, dynamic value stored within the shell’s memory space that is explicitly exported to the environment block of child processes. Unlike standard local shell variables, which are confined to the execution context of the current shell instance, environment variables are inherited by any command, script, or program spawned by the parent shell.

Syntax and Instantiation

In Bash, variables are assigned using the assignment operator (=) with no surrounding whitespace. To promote a shell variable to an environment variable, it must be marked for export using the export builtin or the declare -x command. Standard Export:
Declare Export:
Inline/Temporary Export: Environment variables can be passed to a single child process without modifying the parent shell’s environment block by prepending the assignment directly to the command execution.

Dereferencing (Expansion)

To access the value of an environment variable, the variable name is prefixed with the dollar sign ($), triggering parameter expansion. Curly braces ({}) are used to strictly delimit the variable name from adjacent alphanumeric characters and underscores (_), preventing the shell from misinterpreting the variable’s identifier.

Scope and Inheritance Mechanics

The architectural distinction between a shell variable and an environment variable lies strictly in the export attribute.

Lifecycle and Teardown

Environment variables are ephemeral; their lifecycle is strictly bound to the shell session process (PID) in which they are defined. When the shell process terminates, the environment variables are destroyed. To persist them across sessions, their export statements must be written into shell initialization scripts (e.g., ~/.bashrc, ~/.bash_profile, or /etc/profile). Note: System-wide configuration files like /etc/environment are parsed by PAM (pam_env), not the shell. They strictly require KEY="value" assignments and will throw parsing errors if the export keyword is used. To remove the export attribute from a variable—demoting it back to a local shell variable without destroying its value—use the export builtin with the -n flag. To completely remove the variable from the shell’s memory space, use the unset builtin.

Inspection

Bash provides native builtins to inspect the current environment block and verify exported variables. While external system executables (like GNU Coreutils’ env or printenv) can also display the environment, the strict Bash mechanisms for this are export -p and declare -px.
Tired of Poor Bash Skills? Fix That With Deep Grasping!Learn More