Environment Variables
Environment variables configure how your shell and programs behave. PATH tells the shell where to find commands. HOME points to your home directory. Your apps read database URLs and API keys from them.
View Environment Variables
Common Variables
| Variable | Purpose |
|---|---|
PATH | Directories to search for commands |
HOME | User's home directory |
USER | Current username |
SHELL | Default shell |
EDITOR | Default text editor |
LANG | Language/locale setting |
PWD | Current directory |
Set Variables
Without export, variables are local to the current shell.
Persistent Variables
For Your User: ~/.bashrc
Add:
export EDITOR=vim
export PATH="$HOME/bin:$PATH"
export API_KEY="your-key-here"
Then reload:
Shell Configuration Files
| File | When Loaded |
|---|---|
~/.bashrc | Interactive non-login shells |
~/.bash_profile | Login shells |
~/.profile | Login shells (if no .bash_profile) |
/etc/environment | System-wide, all users |
/etc/profile | System-wide, login shells |
Which File to Use?
For most cases, use ~/.bashrc. For system-wide variables, use /etc/environment.
Modify PATH
Add to ~/.bashrc to make permanent:
# Add custom bin directories
export PATH="$HOME/bin:$HOME/.local/bin:$PATH"
Per-Command Variables
Variable is only set for that command, doesn't affect your shell.
Using .env Files
Common pattern for applications:
# .env file
DATABASE_URL=postgres://localhost/mydb
API_KEY=secret123
DEBUG=true
Load it:
Don't Commit .env
Add .env to .gitignore. Never commit secrets to git.
Check If Variable Is Set
#!/bin/bash
# Check if set
if [[ -z "$API_KEY" ]]; then
echo "API_KEY is not set"
exit 1
fi
# Use default if not set
DB_HOST="${DB_HOST:-localhost}"
Unset Variables
What's the difference between 'VAR=x' and 'export VAR=x'?
Quick Reference
| Command | Purpose |
|---|---|
echo $VAR | View variable |
env | List all variables |
export VAR=value | Set and export |
unset VAR | Remove variable |
source ~/.bashrc | Reload config |
printenv VAR | Print variable value |
Key Takeaways
exportmakes variables available to child processes- Add to
~/.bashrcfor persistence - PATH controls where commands are found
- Use
.envfiles for application config (don't commit them) sourcereloads configuration files- Check required variables at script start
Next: creating shell aliases.