Environment Variable (in the Command-Line)

Share

What is an "Environment Variable" in the Command-Line?

An environment variable is a piece of text that a program has access to that is set by the operating system or by the program that started it to describe the context in which the program is currently running in that is passed down from program to program by default.

Environment variables are different from command-line arguments in that they are "inherited" by default. When a program starts another program, its environment variables are passed down. Programs can alternatively modify the variables they pass to the next program, including adding variables, e.g. with the export statement in Bash, or even removing variables that they had received.

This means if you export foo=42 and start a file manager, the file manager will have the foo environment variable with the value 42 even though there is nothing in its programming to handle such variable. If the file manager starts a different program, e.g. by double clicking on a file, that different program will also inherit the foo variable. This means environment variables can be used to pass arguments that only some programs handle. Programs that don't know what to do with those variables will ignore them, but even as they ignore the variables they will still pass them down by default to any programs they spawn.

Examples of Environment Variables

Some examples of environment variables on Linux are:

  1. PWD: holds the value of the current working directory (present working directory).
  2. USER: holds the username of the user.
  3. HOME: holds the filepath to the home directory of the user.

If you have ever used the terminal on Linux, when you run start a program from the terminal while in a given directory, any other programs that spawn from also operate from the same directory. For example, sudo chmod will execute sudo, and sudo will execute chmod. The reason this works is because sudo gets the PWD variable from the shell, and then sudo passes down that PWD variable to chmod

Written by Noel Santos.

About the Author

I'm a self-taught Brazilian programmer graduated in IT from a FATEC. In a world of increasingly complex and essential computers, I decided to use my technical expertise in hardware, desktop applications, and web technologies to create an informative resource to make PC's easier to understand.

View Comments