Advanced Bash & AutomationLesson 6.4
Environment variables and .env files in Linux
export, env, printenv, .env file pattern, source command, dotenv in scripts, /etc/environment, profile vs bashrc vs bash_profile, secrets management basics
Environment Variables Configure Programs at Runtime
Environment variables are key-value pairs accessible to any process. They are the standard way to pass config, secrets, and runtime settings to programs without hardcoding values. Never commit secrets to source control — use env vars.
Inspecting the Environment
# Print all environment variables
env
printenv
# Print a specific variable
printenv PATH
echo $HOME
# Check if a variable is set
if [[ -z "${DATABASE_URL:-}" ]]; then
echo "DATABASE_URL is not set"
exit 1
fiExporting and .env Files
# Set and export (makes it available to child processes)
export NODE_ENV=production
export PORT=3000
# .env file pattern
# .env contents:
# DATABASE_URL=postgres://user:pass@localhost/mydb
# SECRET_KEY=supersecret
# PORT=8080
# Source it in your script
source .env
# or
. .env
# Pass env vars to a single command without exporting globally
NODE_ENV=test npm testShell Init Files
~/.bashrc runs for every interactive non-login shell. ~/.bash_profile runs for login shells. Put PATH modifications and exports in ~/.bashrc (for interactive use) or /etc/environment (system-wide, all processes).
# Add to ~/.bashrc for permanent PATH addition
export PATH="$HOME/.local/bin:$PATH"