guest@linuxthings: ~/guides/environment.md

guest@linuxthings:~/guides$ man environment

Environment Variables

Environment variables act as placeholders for information stored within the system that passes data to programs launched in shells.

Common Variables

Variable

Description

$HOME

Current user's home directory

$USER

Current user's name

$PATH

List of directories to search for commands

$SHELL

Path to your login shell

$PWD

Current working directory

$OLDPWD

Previous working directory (used by cd -)

$EDITOR / $VISUAL

Default text editor for other programs

$LANG

Language and locale settings

$TERM

Terminal type, e.g. xterm-256color

$PS1

Format of your shell prompt

Managing Variables

printenv           # Print all environment variables
printenv HOME      # Print one variable
echo $HOME         # Print specific variable
MYVAR="data"       # Shell variable, visible only in this shell
export MYVAR       # Export it so child processes inherit it
export MYVAR="data" # Define and export in one step
unset MYVAR        # Remove a variable
env                # List the environment (or run a command with changes)

A plain assignment creates a shell variable that only the current shell can see. export turns it into an environment variable that programs you start from this shell inherit.

One-Off Overrides

Prefix a command with an assignment to change a variable for that command only:

LANG=C sort names.txt       # Sort with the plain C locale
TZ=UTC date                 # Show the time in UTC
EDITOR=nano crontab -e      # Use nano just this once

The Search Path

When you type a command, the shell looks for it in each directory listed in $PATH, from left to right, and runs the first match.

echo $PATH                  # e.g. /usr/local/bin:/usr/bin:/bin
type ls                     # Show where (or what) a command is
PATH="$PATH:$HOME/bin"      # Append a directory for this session

The current directory is deliberately not in $PATH, which is why you run local scripts as ./script.sh.

Making Changes Permanent

Variables set at the prompt disappear when the shell exits. Add them to ~/.bashrc (or ~/.profile for login shells) and reload:

echo 'export PATH="$PATH:$HOME/bin"' >> ~/.bashrc
echo 'export EDITOR=vim' >> ~/.bashrc
source ~/.bashrc            # Apply to the current shell

guest@linuxthings:~/guides$