Environment variables are dynamic values stored in the system that affect how processes and programs behave. They provide a way to pass configuration information to applications and control system behavior without modifying code.
Key Concepts
- Environment Variable: A named value accessible to all processes
- Shell Variable: Local to current shell session only
- Export: Makes shell variables available to child processes
- Scope: Variables can be global (system-wide) or local (user/session)
- Inheritance: Child processes inherit parent’s environment
Command Syntax
export VARIABLE=value - Create/modify environment variable
unset VARIABLE - Remove variable
env - Display all environment variables
printenv [VARIABLE] - Show specific or all variables
Common Options
env -i - Start with empty environment
env -u VAR - Unset specific variable
printenv VAR - Show single variable value
set - Show all variables (shell + environment)
Practical Examples
Example 1: Create and export variable
|
|
Creates variable and makes it available to child processes
Example 2: View all environment variables
|
|
Displays complete environment
Example 3: Temporary variable for command
|
|
Sets variable only for that command execution
Example 4: Check specific variable
|
|
Two ways to display variable content
Use Cases
- Application Configuration: Database URLs, API keys
- System Behavior: Default editors, pagers, browsers
- Path Management: Executable and library locations
- Locale Settings: Language, timezone, formatting
- Development: Compiler flags, library paths
Related Commands
which - Find executable location using PATH
whereis - Locate binary, source, manual files
source - Execute script in current shell
bash -c - Run command in new shell with environment
Common Environment Variables
- PATH: Executable search directories
- HOME: User’s home directory
- USER: Current username
- SHELL: Default shell program
- EDITOR: Default text editor
- LANG: System language/locale
- PWD: Present working directory
- OLDPWD: Previous directory
Configuration Files
/etc/environment- System-wide variables/etc/profile- System-wide shell settings~/.bashrc- User’s bash configuration~/.profile- User’s shell-independent settings~/.bash_profile- User’s bash login settings
Tips & Troubleshooting
Making Variables Persistent
|
|
Common Issues
- Variable not found: Check if exported with
export - Changes don’t persist: Add to appropriate config file
- PATH issues: Verify directory exists and has execute permissions
- Quoting problems: Use quotes for values with spaces
Security Notes
- Never store sensitive data in environment variables in production
- Be cautious with PATH modifications - can be security risk
- Use
env -ito start with clean environment when needed
Debugging
|
|