What Are Environment Variables?
Environment variables are key-value pairs that configure the behavior of processes and applications. They store settings like paths, credentials, and runtime configurations.
Viewing Variables
# Show all environment variables
env
printenv
# Show a specific variable
echo $PATH
echo $HOME
printenv USERSetting Variables
# Set for current session only
export MY_VAR="hello"
export DATABASE_URL="mysql://user:pass@localhost/mydb"
# Set for a single command
DATABASE_URL="..." php artisan migratePersistent Variables
# For current user — add to ~/.bashrc or ~/.profile
echo 'export MY_VAR="hello"' >> ~/.bashrc
source ~/.bashrc
# System-wide — add to /etc/environment
MY_VAR="hello"
# For systemd services
# In the .service file:
Environment=MY_VAR=hello
EnvironmentFile=/etc/myapp/envCommon System Variables
| Variable | Purpose |
|---|---|
PATH | Directories to search for executables |
HOME | Current user home directory |
USER | Current username |
SHELL | Current shell |
LANG | System locale |
EDITOR | Default text editor |
TZ | Timezone |
Application Configuration
Modern applications use environment variables for configuration instead of config files:
# .env file (loaded by frameworks)
DB_HOST=localhost
DB_USER=myapp
DB_PASS=secretpassword
REDIS_URL=redis://localhost:6379
API_KEY=sk_live_xxxSecurity
- Never commit
.envfiles to version control - Use
chmod 600 .envto restrict access - Environment variables in
docker run -eare visible indocker inspect