π Environment Variables
π― What You Will Learnβ
- Understand what environment variables are and how they differ from normal variables.
- Learn how they are created, exported, listed, modified, and persisted.
- Explore system and user-level variable configuration files (
.bashrc,/etc/environment). - Pass environment data across subshells, cron jobs, and WP-CLI scripts.
- Apply environment variable management to WordPress VPS automation.
- Safely debug and verify variable states during runtime.
1. 5W + 1H Frameworkβ
| Element | Description |
| What | Environment variables are keyβvalue pairs defining configuration and behavior for user sessions and processes. |
| Why | They allow flexible and reusable configuration across scripts, shells, and applications without hardcoding values. |
| Who | System administrators, Bash developers, and WordPress VPS engineers maintaining multiple environments. |
| Where | Stored in profile files like /etc/environment, /etc/profile, ~/.bashrc, and ~/.profile. |
| When | When controlling system paths, app configurations, or running WordPress scripts under different environments. |
| How | Use export, env, or printenv to define and view environment variables; modify profile files for persistence. |
2. Prerequisitesβ
- Completed Module 3.1 (Variable Declaration).
- Understanding of
bashrc, profile files, and Linux user sessions. - Access to a VPS environment with root privileges.
3. Core Syntax & Concept (Expanded and Factual)β
| No | Syntax Formula | Command / Type | Syntax Example | Description | Behavior / Output |
| 1 | export NAME=value | Create Environment Variable | export WP_ENV=production | Creates a new environment variable available to subshells and child processes. | Variable persists within current session. |
| 2 | NAME=value | Shell Variable (non-exported) | WP_ENV=staging | Defines variable only for current shell. | Not inherited by child shells. |
| 3 | echo $NAME | Reference Variable | echo $PATH | Prints the value of an environment variable. | Displays variableβs content. |
| 4 | env | List All Environment Variables | env | Lists all exported environment variables. | Prints full environment list. |
| 5 | printenv | View Environment Variable | printenv HOME | Shows value of a specific environment variable. | Displays only selected variable. |
| 6 | set | List Shell + Environment Variables | `set | less` | Displays both shell and environment variables. |
| 7 | export -p | List All Exported Variables | `export -p | grep WP_` | Lists all variables currently exported to environment. |
| 8 | declare -x NAME=value | Alternate Export Syntax | declare -x PHP_VER=8.3 | Equivalent to export. Preferred for clarity in scripts. | Creates global variable. |
| 9 | unset NAME | Remove Variable | unset WP_ENV | Deletes an environment or shell variable. | Variable no longer exists. |
| 10 | export NAME=$(command) | Dynamic Assignment | export TODAY=$(date +%F) | Assigns command output to environment variable. | Command executes; result stored. |
| 11 | readonly NAME=value | Read-Only Variable | readonly SHELL_TYPE=bash | Prevents modification or unsetting. | Immutable within session. |
| 12 | export -n NAME | Unexport Variable | export -n WP_ENV | Removes export property, keeps it local. | Variable no longer global. |
| 13 | env -i command | Run Command in Empty Environment | env -i bash | Executes command with a clean, minimal environment. | Isolated environment. |
| 14 | env VAR=value command | Temporary Environment Variable | env WP_ENV=dev wp plugin list | Sets variable only for duration of command. | Reverts after command ends. |
| 15 | `printenv | grep keyword` | Filtered Listing | `printenv | grep PHP` |
| 16 | source ~/.bashrc | Reload Environment | source ~/.bashrc | Reloads updated user environment variables. | Applies new settings immediately. |
| 17 | . ~/.profile | POSIX Reload Method | . ~/.profile | Equivalent to source, ensures compatibility. | Loads profile variables. |
| 18 | /etc/environment | System-Wide Persistent Vars | export BACKUP_DIR=/home/wpbackup | File used for persistent variables across all users. | Loaded on login. |
| 19 | `printenv | sort` | Inspect Organized Output | `printenv | sort |
| 20 | `env | grep -E 'PATH | USER'` | Combined Filter Example | `env |
| 21 | echo $0 | Identify Shell | echo $0 | Displays current shell name (bash, sh, zsh). | Useful when debugging variable scope. |
| 22 | export PATH=$PATH:/new/path | Extend Environment Variable | export PATH=$PATH:/usr/local/bin | Adds directories to $PATH. | Appends without overwriting. |
| 23 | printenv SHELL | Display Current Shell Path | printenv SHELL | Shows location of current shell binary. | Example: /bin/bash. |
| 24 | envsubst | Substitute Environment Variables in Files | envsubst < input.conf > output.conf | Replaces variables with their values. | Dynamic templating for scripts. |
| 25 | `grep -E 'export | declare' ~/.bashrc` | Inspect User Exports | grep export ~/.bashrc | Checks whatβs defined permanently in config. |
| 26 | cat /proc/$$/environ | Inspect Raw Environment | `cat /proc/$$/environ | tr '\0' '\n'` | Displays environment vars at process level. |
4. Demonstration Exampleβ
Input Script:
#!/bin/bash
export WP_ENV="production"
export BACKUP_DIR="/home/wpbackup"
export TODAY=$(date +%F)
export PHP_MEMORY_LIMIT="512M"
echo "Environment: $WP_ENV"
echo "Backup directory: $BACKUP_DIR"
echo "Today's date: $TODAY"
echo "PHP Memory Limit: $PHP_MEMORY_LIMIT"
Expected Output:
Environment: production
Backup directory: /home/wpbackup
Today's date: 2025-10-09
PHP Memory Limit: 512M
Explanation: All exported variables are accessible globally, including subshells and child processes like WP-CLI or cron tasks.β
5. Use Cases (WordPress-VPS Focused)β
5.1 Persistent Server-Wide Environment Setupβ
sudo nano /etc/environment
# Add:
WP_PATH="/var/www/html"
BACKUP_DIR="/home/wpbackup"
PHP_MEMORY_LIMIT="512M"
Use Case: Keeps WP configuration and backup directories consistent across all users and reboots.β
5.2 Temporary Environment Variables for WP Commandsβ
env WP_ENV=staging wp plugin update --all --allow-root
Expected Output:
Success: Updated 10 of 10 plugins.
Use Case: Quickly test or perform actions under different WP environments without permanent change.β
5.3 Dynamic Assignment for Loggingβ
export LOG_DATE=$(date +%F_%H-%M)
echo "Backup started at $LOG_DATE"
Expected Output:
Backup started at 2025-10-09_19-45
Use Case: Automates time-stamped log or backup filenames.β
5.4 Clean Session Testingβ
env -i bash
echo $PATH
Expected Output:
(blank)
Use Case: Test minimal environment for troubleshooting WP scripts without interference from global settings.β
5.5 Using envsubst for Config Templatesβ
export DB_NAME=wp_main
export DB_USER=wp_user
export DB_PASS=securepass
cat <<EOF > config_template.conf
database=${DB_NAME}
user=${DB_USER}
password=${DB_PASS}
EOF
envsubst < config_template.conf > wpconfig_ready.conf
cat wpconfig_ready.conf
Expected Output:
database=wp_main
user=wp_user
password=securepass
Use Case: Generate dynamic configuration files using environment variable substitution.β
6. Best Practicesβ
| Practice | Description |
| Always quote variables containing spaces | e.g., export PATH="/usr/local/bin:/usr/bin". |
Avoid redefining core system vars like $HOME or $SHELL. | |
For permanent variables, use ~/.bashrc or /etc/environment. | |
Prefix application-specific vars (WP_, DB_) for clarity. | |
Use envsubst or template files for injecting env values safely. | |
Re-source session after edits with source ~/.bashrc. | |
| Keep sensitive values (passwords) restricted with correct file permissions. |
7. Common Mistakes & Fixesβ
| Mistake | Wrong Example | Correct Example | Explanation |
Space around = | export WP_ENV = production | export WP_ENV=production | Bash treats space as syntax error. |
Missing export | WP_ENV=staging | export WP_ENV=staging | Variable not inherited by subshells. |
Overwriting $PATH | export PATH=/usr/local/bin | export PATH=$PATH:/usr/local/bin | Must append, not overwrite. |
| Unreloaded session | source ~/.bashrc missing | source ~/.bashrc | Reload needed after file edits. |
| Exposing secrets | echo $DB_PASS in logs | Store secrets in .env with chmod 600 | Avoid leaking sensitive data. |
8. Quick Lab β Global WP Environment Setupβ
Script: wp_env_global.sh
#!/bin/bash
# --------------------------------------------
# Script Name: wp_env_global.sh
# Purpose: Define and verify environment variables
# --------------------------------------------
export WP_ENV="production"
export WP_PATH="/var/www/html"
export BACKUP_DIR="/home/wpbackup"
export PHP_VER="8.3"
export TODAY=$(date +%F)
echo "π Environment: $WP_ENV"
echo "π WordPress Path: $WP_PATH"
echo "πΎ Backup Directory: $BACKUP_DIR"
echo "βοΈ PHP Version: $PHP_VER"
echo "π
Today: $TODAY"
Expected Output:
π Environment: production
π WordPress Path: /var/www/html
πΎ Backup Directory: /home/wpbackup
βοΈ PHP Version: 8.3
π
Today: 2025-10-09
Explanation: All variables are globally accessible, simplifying other script integrations like WP-CLI updates or backup automations.β
9. Troubleshooting Matrixβ
| Issue | Symptom | Cause | Solution |
| Variable not found | echo $VAR returns blank | Variable unset or unexported | Run export VAR=value. |
| Not persistent after reboot | Reset after login | Defined only in current session | Add to .bashrc or /etc/environment. |
| Command not working | PATH lost | Overwrote $PATH | Restore default or append instead. |
| Wrong env variable value in cron | Different shell context | Cron uses /bin/sh | Define variables inside cron script or use absolute path. |
| Exposed credentials | Visible via printenv | Sensitive vars unprotected | Move to .env file and secure permissions. |
10. Static vs Dynamic Framingβ
| Framing | Description | Behavior |
| Static | Predefined, persistent variables in config files | Stable, ideal for constants like $WP_PATH. |
| Dynamic | Runtime variables from commands or scripts | Auto-updates each run (e.g., timestamps, runtime state). |
11. Cheat Sheetβ
| Task | Command Example |
| Create variable | export NAME=value |
| Print variable | echo $NAME |
| Remove variable | unset NAME |
| List all env vars | env |
| Show one var | printenv NAME |
| Temporary variable | env NAME=value command |
| Reload session | source ~/.bashrc |
| Persistent vars | Add to /etc/environment |
| Substitute vars in file | envsubst < in > out |
| Append to PATH | export PATH=$PATH:/usr/local/bin |
12. Mini-Quizβ
| # | Question | Answer |
| 1 | Which command lists all environment variables? | env |
| 2 | How to make a variable available to subshells? | Use export. |
| 3 | Where are persistent environment variables stored? | In ~/.bashrc or /etc/environment. |
| 4 | What command reloads your shell environment? | source ~/.bashrc |
| 5 | How to assign a dynamic value to an env variable? | export VAR=$(command) |