Skip to main content

πŸ“˜ Environment Variables



🎯 What You Will Learn​

  1. Understand what environment variables are and how they differ from normal variables.
  2. Learn how they are created, exported, listed, modified, and persisted.
  3. Explore system and user-level variable configuration files (.bashrc, /etc/environment).
  4. Pass environment data across subshells, cron jobs, and WP-CLI scripts.
  5. Apply environment variable management to WordPress VPS automation.
  6. Safely debug and verify variable states during runtime.

1. 5W + 1H Framework​

ElementDescription
WhatEnvironment variables are key–value pairs defining configuration and behavior for user sessions and processes.
WhyThey allow flexible and reusable configuration across scripts, shells, and applications without hardcoding values.
WhoSystem administrators, Bash developers, and WordPress VPS engineers maintaining multiple environments.
WhereStored in profile files like /etc/environment, /etc/profile, ~/.bashrc, and ~/.profile.
WhenWhen controlling system paths, app configurations, or running WordPress scripts under different environments.
HowUse 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)​

NoSyntax FormulaCommand / TypeSyntax ExampleDescriptionBehavior / Output
1export NAME=valueCreate Environment Variableexport WP_ENV=productionCreates a new environment variable available to subshells and child processes.Variable persists within current session.
2NAME=valueShell Variable (non-exported)WP_ENV=stagingDefines variable only for current shell.Not inherited by child shells.
3echo $NAMEReference Variableecho $PATHPrints the value of an environment variable.Displays variable’s content.
4envList All Environment VariablesenvLists all exported environment variables.Prints full environment list.
5printenvView Environment Variableprintenv HOMEShows value of a specific environment variable.Displays only selected variable.
6setList Shell + Environment Variables`setless`Displays both shell and environment variables.
7export -pList All Exported Variables`export -pgrep WP_`Lists all variables currently exported to environment.
8declare -x NAME=valueAlternate Export Syntaxdeclare -x PHP_VER=8.3Equivalent to export. Preferred for clarity in scripts.Creates global variable.
9unset NAMERemove Variableunset WP_ENVDeletes an environment or shell variable.Variable no longer exists.
10export NAME=$(command)Dynamic Assignmentexport TODAY=$(date +%F)Assigns command output to environment variable.Command executes; result stored.
11readonly NAME=valueRead-Only Variablereadonly SHELL_TYPE=bashPrevents modification or unsetting.Immutable within session.
12export -n NAMEUnexport Variableexport -n WP_ENVRemoves export property, keeps it local.Variable no longer global.
13env -i commandRun Command in Empty Environmentenv -i bashExecutes command with a clean, minimal environment.Isolated environment.
14env VAR=value commandTemporary Environment Variableenv WP_ENV=dev wp plugin listSets variable only for duration of command.Reverts after command ends.
15`printenvgrep keyword`Filtered Listing`printenvgrep PHP`
16source ~/.bashrcReload Environmentsource ~/.bashrcReloads updated user environment variables.Applies new settings immediately.
17. ~/.profilePOSIX Reload Method. ~/.profileEquivalent to source, ensures compatibility.Loads profile variables.
18/etc/environmentSystem-Wide Persistent Varsexport BACKUP_DIR=/home/wpbackupFile used for persistent variables across all users.Loaded on login.
19`printenvsort`Inspect Organized Output`printenvsort
20`envgrep -E 'PATHUSER'`Combined Filter Example`env
21echo $0Identify Shellecho $0Displays current shell name (bash, sh, zsh).Useful when debugging variable scope.
22export PATH=$PATH:/new/pathExtend Environment Variableexport PATH=$PATH:/usr/local/binAdds directories to $PATH.Appends without overwriting.
23printenv SHELLDisplay Current Shell Pathprintenv SHELLShows location of current shell binary.Example: /bin/bash.
24envsubstSubstitute Environment Variables in Filesenvsubst < input.conf > output.confReplaces variables with their values.Dynamic templating for scripts.
25`grep -E 'exportdeclare' ~/.bashrc`Inspect User Exportsgrep export ~/.bashrcChecks what’s defined permanently in config.
26cat /proc/$$/environInspect Raw Environment`cat /proc/$$/environtr '\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​

PracticeDescription
Always quote variables containing spacese.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​

MistakeWrong ExampleCorrect ExampleExplanation
Space around =export WP_ENV = productionexport WP_ENV=productionBash treats space as syntax error.
Missing exportWP_ENV=stagingexport WP_ENV=stagingVariable not inherited by subshells.
Overwriting $PATHexport PATH=/usr/local/binexport PATH=$PATH:/usr/local/binMust append, not overwrite.
Unreloaded sessionsource ~/.bashrc missingsource ~/.bashrcReload needed after file edits.
Exposing secretsecho $DB_PASS in logsStore secrets in .env with chmod 600Avoid 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​

IssueSymptomCauseSolution
Variable not foundecho $VAR returns blankVariable unset or unexportedRun export VAR=value.
Not persistent after rebootReset after loginDefined only in current sessionAdd to .bashrc or /etc/environment.
Command not workingPATH lostOverwrote $PATHRestore default or append instead.
Wrong env variable value in cronDifferent shell contextCron uses /bin/shDefine variables inside cron script or use absolute path.
Exposed credentialsVisible via printenvSensitive vars unprotectedMove to .env file and secure permissions.

10. Static vs Dynamic Framing​

FramingDescriptionBehavior
StaticPredefined, persistent variables in config filesStable, ideal for constants like $WP_PATH.
DynamicRuntime variables from commands or scriptsAuto-updates each run (e.g., timestamps, runtime state).

11. Cheat Sheet​

TaskCommand Example
Create variableexport NAME=value
Print variableecho $NAME
Remove variableunset NAME
List all env varsenv
Show one varprintenv NAME
Temporary variableenv NAME=value command
Reload sessionsource ~/.bashrc
Persistent varsAdd to /etc/environment
Substitute vars in fileenvsubst < in > out
Append to PATHexport PATH=$PATH:/usr/local/bin

12. Mini-Quiz​

#QuestionAnswer
1Which command lists all environment variables?env
2How to make a variable available to subshells?Use export.
3Where are persistent environment variables stored?In ~/.bashrc or /etc/environment.
4What command reloads your shell environment?source ~/.bashrc
5How to assign a dynamic value to an env variable?export VAR=$(command)