2.4.1. The Shell Environment: Variables, Paths, and Configs
💡 First Principle: Environment variables are key-value pairs that programs inherit from their parent process. When you run a script, it inherits a copy of your shell's environment. Changes to variables inside the script don't affect the parent shell — unless you source the script instead of executing it.
Important Environment Variables:
| Variable | Purpose | Example Value |
|---|---|---|
PATH | Directories searched for commands (colon-separated) | /usr/local/bin:/usr/bin:/bin |
HOME | Current user's home directory | /home/alice |
USER | Current username | alice |
SHELL | Path to current shell binary | /bin/bash |
PS1 | Primary prompt string | [\u@\h \W]\$ |
DISPLAY | X11 display server (for GUI apps via SSH) | :0 or localhost:10.0 |
env # Print all environment variables
printenv PATH # Print a specific variable
export MY_VAR="hello" # Set and export to child processes
unset MY_VAR # Remove a variable
echo $PATH # Print PATH value
PATH="$PATH:/opt/myapp/bin" # Append to PATH (current session only)
Shell Configuration Files — Load Order:
Login shell: /etc/profile → FIRST found of ~/.bash_profile, ~/.bash_login, ~/.profile
Interactive non-login: /etc/bash.bashrc → ~/.bashrc
Non-interactive: $BASH_ENV (rarely set)
source ~/.bashrc # Reload without opening new shell
. ~/.bashrc # Equivalent (dot is alias for source)
Path Types:
# Absolute — always starts from /
cd /etc/nginx
cat /home/alice/notes.txt
~ # Expands to $HOME (/home/alice)
# Relative — from current directory
cd .. # Go up one level
cd - # Return to previous directory
./script.sh # Run script in current directory
ls ../../etc # Up two levels, into etc
Aliases:
alias ll='ls -la' # Create alias (current session)
alias grep='grep --color=auto'
unalias ll # Remove alias
alias # List all aliases
To make aliases persistent, add them to ~/.bashrc.
⚠️ Exam Trap: Variables set without export are local to the current shell — child processes (scripts, subshells) do not inherit them. export VAR=value makes the variable available to all child processes. This is why a variable you set in your shell may not be visible to a script you run.
Reflection Question: A cron job runs a script that needs to find binaries in /opt/myapp/bin, but it fails with "command not found" even though those commands work fine when you run the script manually. What environment variable is most likely the cause, and how do you fix it?