SkillSprout
Chapter 1 · Lesson 7
Intermediate
1 min read

Environment Variables and the Shell Environment

Overview

A shell variable belongs to the shell. An environment variable is exported to child processes. Programs read environment variables to discover configuration such as PATH, HOME, locale and API settings.

Detailed Notes

Inspect variables

bash
echo "$HOME"
echo "$USER"
echo "$PATH"
env
printenv USER

Variable names are commonly uppercase but not required. echo "$USER" is safer than echo $USER because quotes prevent whitespace or glob expansion.

Shell variable versus environment variable

bash
APP_MODE=development
echo "$APP_MODE"

This variable exists only in the shell. A child process does not inherit it.

bash
export APP_MODE=development
sh -c 'echo "$APP_MODE"'

export places the variable in the environment of new child processes.

Remove a variable:

bash
unset APP_MODE

PATH

PATH is a colon-separated list of directories containing executable programs:

bash
echo "$PATH"

Add a directory for the current shell:

bash
export PATH="$HOME/.local/bin:$PATH"

Do not add . to PATH in a production system. It can execute a malicious local file when a common command name is typed.

Common Interview Questions

Finished this lesson?

0 of 25 lessons done · 0% of the course