π Variable Declaration
π― What You Will Learnβ
- Understand how to declare, assign, and reference variables in Bash.
- Learn the difference between local and global variables.
- Practice naming conventions, valid characters, and scope rules.
- Prevent variable overwrites and unexpected behavior in scripts.
- Use variables effectively in WordPress automation (backups, updates, configs).
- Apply best practices for readability and portability in VPS environments.
1. 5W + 1H Frameworkβ
| Element | Description |
| What | A variable is a named memory reference used to store data (string, number, path, etc.) in Bash. |
| Why | Variables allow reusability, configurability, and clean code β essential for automation scripts. |
| Who | System administrators, Bash developers, and WordPress engineers automating VPS workflows. |
| Where | In any Bash shell or script file (.sh), often inside /usr/local/bin or /home/scripts/. |
| When | When storing credentials, directory paths, or script configuration data. |
| How | Use var=value to define and $var or ${var} to reference it. |
2. Prerequisitesβ
- Completed Module 2.5 (Comments).
- Familiarity with basic Bash syntax and file execution.
- Working knowledge of environment variables like
$HOMEor$PATH.
3. Core Syntax & Conceptβ
| No | Syntax Formula | Type | Syntax Example | Description | Output Behavior |
| 1 | name=value | Basic Declaration | site="WordPress" | Assigns string or number; no spaces around =. | Creates variable in current shell. |
| 2 | $name | Reference Variable | echo $site | Retrieves variable content. | Prints variableβs value. |
| 3 | ${name} | Braced Reference | echo "Welcome to ${site}!" | Safer form for concatenation or complex names. | Expands variable correctly. |
| 4 | readonly name=value | Constant Declaration | readonly author="Donny" | Prevents further modification. | Immutable variable. |
| 5 | unset name | Delete Variable | unset site | Removes variable from memory. | Variable no longer exists. |
| 6 | declare -i name=value | Integer Variable | declare -i count=5 | Stores arithmetic-only value. | Treated as number. |
| 7 | declare -r name=value | Read-Only Variable | declare -r wp_path="/var/www/html" | Makes variable unchangeable. | Permanent for session. |
| 8 | local name=value | Local Variable (in function) | local status="active" | Restricts variable scope inside function. | Exists only within function. |
| 9 | export name=value | Environment Variable | export PATH=$PATH:/usr/local/bin | Makes variable accessible to child processes. | Available system-wide. |
| 10 | name=$(command) | Command Substitution | today=$(date +%F) | Assigns command output to variable. | Executes and stores output. |
| 11 | declare -p name | Inspect Variable | declare -p site | Displays variable type and value. | Prints definition. |
| 12 | typeset name=value | Alternate Declaration (POSIX) | typeset version="1.2" | Similar to declare, legacy compatible. | Sets variable accordingly. |
4. Demonstration Exampleβ
Input Script:
#!/bin/bash
site="WordPress"
path="/var/www/html"
today=$(date +%F)
echo "Site: $site"
echo "Path: $path"
echo "Backup Date: $today"
Expected Output:
Site: WordPress
Path: /var/www/html
Backup Date: 2025-10-09
Explanation:
Variables are declared using name=value with no spaces. Values are accessed using $name or ${name}.β
5. Use Cases (WordPress-VPS Focused)β
5.1 (Ref: #1) β Basic Declaration for Site Metadataβ
Input:
site="metaxenith.com"
echo "Deploying for $site..."
Expected Output:
Deploying for metaxenith.com...
Explanation: Simple variable assignment for flexible automation scripts. Use Case: For domain-specific deployment scripts.β
5.2 (Ref: #3) β Using Braced Variables for Safe Expansionβ
Input:
project="wpstrategist"
echo "Project directory: /home/${project}/public_html/"
Expected Output:
Project directory: /home/wpstrategist/public_html/
Explanation: Braces prevent ambiguity when concatenating. Use Case: Used when combining paths or filenames dynamically.β
5.3 (Ref: #4) β Creating Immutable Script Variablesβ
Input:
readonly author="Donny"
echo "Author: $author"
author="John" # Attempt to change
Expected Output:
Author: Donny
bash: author: readonly variable
Explanation: Prevents accidental overwrite of critical metadata. Use Case: Protect script-level constants like version or author.β
5.4 (Ref: #8) β Local Variables in Functionsβ
Input:
function wp_backup() {
local folder="/home/wpbackup"
echo "Backing up to $folder..."
}
wp_backup
echo "Outside: $folder"
Expected Output:
Backing up to /home/wpbackup...
Outside:
Explanation: Local variable exists only inside function. Use Case: Isolates variable scope in modular WP scripts.β
5.5 (Ref: #9) β Exporting Environment Variablesβ
Input:
export WP_ENV="production"
echo "Current WP environment: $WP_ENV"
Expected Output:
Current WP environment: production
Explanation:
export makes variable available to child processes or subshells.
Use Case: Pass environment mode (staging, production, etc.) to WP-CLI tasks.β
5.6 (Ref: #10) β Storing Command Outputβ
Input:
backup_date=$(date +%F)
echo "Backup filename: site_$backup_date.tar.gz"
Expected Output:
Backup filename: site_2025-10-09.tar.gz
Explanation: Uses command substitution to insert dynamic values. Use Case: Automate file naming for backups and logs.β
5.7 (Ref: #6) β Integer Variable Exampleβ
Input:
declare -i count=5
count+=10
echo "Total count: $count"
Expected Output:
Total count: 15
Explanation:
declare -i ensures arithmetic behavior.
Use Case: Counting sites, users, or backup iterations.β
5.8 (Ref: #5) β Unset Variables for Cleanupβ
Input:
tmp_file="/home/tmp/test.txt"
echo "Temp file: $tmp_file"
unset tmp_file
echo "After unset: $tmp_file"
Expected Output:
Temp file: /home/tmp/test.txt
After unset:
Explanation: Releases variable to avoid memory or data leaks. Use Case: For cleaning temporary paths in automation jobs.β
6. Best Practicesβ
| Practice | Description |
Avoid spaces around = | Bash treats it as syntax error. |
Always quote variables ("$var") | Prevents issues with spaces in values. |
| Use uppercase for constants | Improves readability (e.g., BACKUP_DIR). |
| Prefix local vars inside functions | Prevents global overrides. |
Use braces for concatenation (${var}_suffix) | Avoid misinterpretation. |
| Use descriptive names | e.g., wp_backup_path, db_name, env_mode. |
7. Common Mistakes & Fixesβ
| Mistake | Wrong Example | Correct Example | Explanation |
Space around = | site = "WordPress" | site="WordPress" | Spaces invalidate assignment. |
Forgetting $ when referencing | echo site | echo $site | $ required to retrieve value. |
| Overwriting constants | readonly version="1.0" then version="2.0" | Donβt modify readonly vars. | Read-only variable is immutable. |
| Using undefined variable | echo $notset | Define before use. | Returns blank or error if unset. |
8. Quick Lab β WordPress Environment Configβ
Script: wp_env_config.sh
#!/bin/bash
# -----------------------------------------
# Script Name: wp_env_config.sh
# Purpose: Manage WordPress environment variables
# -----------------------------------------
SITE_NAME="wpstrategist.com"
WP_PATH="/var/www/html"
ENV_MODE="production"
TODAY=$(date +%F)
echo "π§ Configuring $SITE_NAME..."
echo "Path: $WP_PATH"
echo "Mode: $ENV_MODE"
echo "Date: $TODAY"
Expected Output:
π§ Configuring wpstrategist.com...
Path: /var/www/html
Mode: production
Date: 2025-10-09
Explanation: Demonstrates practical use of multiple variables for WP automation scripts.β
9. Troubleshooting Matrixβ
| Issue | Symptom | Cause | Solution |
| βcommand not foundβ error | Variable unexpanded | Forgot $ prefix | Always use $name or ${name}. |
| Empty variable | Output blank | Variable unset or misspelled | Check with declare -p name. |
| Permission denied | Cannot change variable | Declared readonly | Remove readonly or restart shell. |
| Variable lost after script ends | Value disappears | Not exported | Use export var=value for persistence. |
10. Static vs Dynamic Framingβ
| Framing | Description | Behavior |
| Static | Hardcoded assignments (e.g., site="wpstrategist") | Reliable but not adaptable. |
| Dynamic | Variables based on input or commands | More flexible and automated. |
11. Cheat Sheetβ
| Task | Syntax / Example |
| Declare variable | var=value |
| Access variable | $var |
| Read-only variable | readonly var=value |
| Remove variable | unset var |
| Export variable | export var=value |
| Local variable (function) | local var=value |
| Command substitution | var=$(command) |
| Inspect variable | declare -p var |
12. Mini-Quizβ
| # | Question | Answer |
| 1 | Whatβs the correct syntax to assign a value in Bash? | name=value |
| 2 | How do you print the value of a variable? | echo $name |
| 3 | What happens if you use spaces around =? | Syntax error. |
| 4 | How do you make a variable read-only? | readonly name=value |
| 5 | Which command removes a variable from memory? | unset name |