Bash – What Exactly is an Environment Variable?

bashenvironment-variablesshell

I know that VARIABLE=value creates an environment variable, and export VARIABLE=value makes it available to processes created by the current shell. env shows the current environment variables, but where do they live? What comprises an environment variable (or an environment, for that matter)?

Best Answer

An environment is not as magical as it might seem. The shell stores it in memory and passes to the execve() system call. The child process inherits it as an array pointer called environ. From the execve manpage:

SYNOPSIS

   #include <unistd.h>

   int execve(const char *filename, char *const argv[],
              char *const envp[]);

argv is an array of argument strings passed to the new program.
By convention, the first of these strings should contain the filename associated with the file being executed. envp is an array of strings, conventionally of the form key=value, which are passed as environment to the new program.

The environ(7) manpage also offers some insight:

SYNOPSIS

   extern char **environ;

DESCRIPTION

The variable environ points to an array of pointers to strings called the "environment". The last pointer in this array has the value NULL. (This variable must be declared in the user program, but is declared in the header file <unistd.h> in case the header files came from libc4 or libc5, and in case they came from glibc and _GNU_SOURCE was defined.) This array of strings is made available to the process by the exec(3) call that started the process.

Both of these GNU manpages match the POSIX specification

Related Question