Skip to main content

πŸ“˜ Variable Declaration



🎯 What You Will Learn​

  1. Understand how to declare, assign, and reference variables in Bash.
  2. Learn the difference between local and global variables.
  3. Practice naming conventions, valid characters, and scope rules.
  4. Prevent variable overwrites and unexpected behavior in scripts.
  5. Use variables effectively in WordPress automation (backups, updates, configs).
  6. Apply best practices for readability and portability in VPS environments.

1. 5W + 1H Framework​

ElementDescription
WhatA variable is a named memory reference used to store data (string, number, path, etc.) in Bash.
WhyVariables allow reusability, configurability, and clean code β€” essential for automation scripts.
WhoSystem administrators, Bash developers, and WordPress engineers automating VPS workflows.
WhereIn any Bash shell or script file (.sh), often inside /usr/local/bin or /home/scripts/.
WhenWhen storing credentials, directory paths, or script configuration data.
HowUse 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 $HOME or $PATH.

3. Core Syntax & Concept​

NoSyntax FormulaTypeSyntax ExampleDescriptionOutput Behavior
1name=valueBasic Declarationsite="WordPress"Assigns string or number; no spaces around =.Creates variable in current shell.
2$nameReference Variableecho $siteRetrieves variable content.Prints variable’s value.
3${name}Braced Referenceecho "Welcome to ${site}!"Safer form for concatenation or complex names.Expands variable correctly.
4readonly name=valueConstant Declarationreadonly author="Donny"Prevents further modification.Immutable variable.
5unset nameDelete Variableunset siteRemoves variable from memory.Variable no longer exists.
6declare -i name=valueInteger Variabledeclare -i count=5Stores arithmetic-only value.Treated as number.
7declare -r name=valueRead-Only Variabledeclare -r wp_path="/var/www/html"Makes variable unchangeable.Permanent for session.
8local name=valueLocal Variable (in function)local status="active"Restricts variable scope inside function.Exists only within function.
9export name=valueEnvironment Variableexport PATH=$PATH:/usr/local/binMakes variable accessible to child processes.Available system-wide.
10name=$(command)Command Substitutiontoday=$(date +%F)Assigns command output to variable.Executes and stores output.
11declare -p nameInspect Variabledeclare -p siteDisplays variable type and value.Prints definition.
12typeset name=valueAlternate 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​

PracticeDescription
Avoid spaces around =Bash treats it as syntax error.
Always quote variables ("$var")Prevents issues with spaces in values.
Use uppercase for constantsImproves readability (e.g., BACKUP_DIR).
Prefix local vars inside functionsPrevents global overrides.
Use braces for concatenation (${var}_suffix)Avoid misinterpretation.
Use descriptive namese.g., wp_backup_path, db_name, env_mode.

7. Common Mistakes & Fixes​

MistakeWrong ExampleCorrect ExampleExplanation
Space around =site = "WordPress"site="WordPress"Spaces invalidate assignment.
Forgetting $ when referencingecho siteecho $site$ required to retrieve value.
Overwriting constantsreadonly version="1.0" then version="2.0"Don’t modify readonly vars.Read-only variable is immutable.
Using undefined variableecho $notsetDefine 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​

IssueSymptomCauseSolution
β€œcommand not found” errorVariable unexpandedForgot $ prefixAlways use $name or ${name}.
Empty variableOutput blankVariable unset or misspelledCheck with declare -p name.
Permission deniedCannot change variableDeclared readonlyRemove readonly or restart shell.
Variable lost after script endsValue disappearsNot exportedUse export var=value for persistence.

10. Static vs Dynamic Framing​

FramingDescriptionBehavior
StaticHardcoded assignments (e.g., site="wpstrategist")Reliable but not adaptable.
DynamicVariables based on input or commandsMore flexible and automated.

11. Cheat Sheet​

TaskSyntax / Example
Declare variablevar=value
Access variable$var
Read-only variablereadonly var=value
Remove variableunset var
Export variableexport var=value
Local variable (function)local var=value
Command substitutionvar=$(command)
Inspect variabledeclare -p var

12. Mini-Quiz​

#QuestionAnswer
1What’s the correct syntax to assign a value in Bash?name=value
2How do you print the value of a variable?echo $name
3What happens if you use spaces around =?Syntax error.
4How do you make a variable read-only?readonly name=value
5Which command removes a variable from memory?unset name