Skip to main content

πŸ“˜ Bash Scripting Curriculum – Focused on Core Capabilities (WordPress Server Context)


1. Bash Fundamentals & Environment Setup​

1.1 Introduction​


1.2 Environment Setup​

Introduction​

User-Specific Configuration​

System-Wide Configuration​

Core Customization Techniques​

Advanced Setup​


2. Syntax & Command Structure
​

2.1 Exit Status Codes​


2.2 Command Grouping​


2.3 Command Listing & Chaining​


2.4 Comments, Quoting & Escaping​

Comments​

Quoting & Escaping​


3. Script Execution & Automation Basics
​

3.1. Introduction to Script Execution​

  • 3.1.1 What Is a Bash Script? Purpose, typical use cases, and how scripts differ from interactive commands.
  • 3.1.2 Running Scripts Running scripts
  • Execution methods: bash script.sh, ./script.sh, source script.sh
  • Permissions and chmod +x
  • Relative vs absolute paths
  • Expected CLI output and troubleshooting β€œpermission denied” errors

3.2. Shebang & Interpreter Control​

  • 3.2.1 Understanding the Shebang Line (#!) Shebang
  • Syntax and placement (first line rule)
  • Common interpreters (#!/bin/bash, #!/usr/bin/env bash)
  • Portability considerations between systems
  • 3.2.2 Debugging Shebang Errors
  • Handling bad interpreter issues
  • Using env for portable paths

3.3. Execution Context & Environment​

  • Execution Context & Environment
  • Difference between login shells, non-login shells, and subshells
  • How environment variables propagate (export, inheritance, env command)
  • Sourcing external files (., source)
  • Isolation and side effects when running scripts

3.4. Script Structure & Lifecycle​

  • Script Structure & Lifecycle
  • Recommended file header: metadata, author, description, usage example
  • Code blocks: variables, functions, logic flow
  • Input handling ($1, $@, read)
  • Output and logging (echo, printf, redirection)
  • Exit strategy (exit, status codes, error handling)
  • Lifecycle stages: creation β†’ testing β†’ production deployment

3.5. Basic Automation Hooks​

  • Basic automation hooks
  • Using cron jobs for scheduled automation
  • at command for one-time tasks
  • Integrating scripts with systemd services
  • File and event-triggered automation (e.g., inotifywait)
  • Real-world examples: automatic WordPress backup, log cleanup, and cache flush

3.6. Hands-On Labs & Troubleshooting​

  • Build your first executable .sh script
  • Test Shebang portability
  • Automate a recurring task using cron
  • Debug common script failures (set -x, bash -n)
  • Logging automation output and email notifications

3.7. Best Practices & Next Steps​

  • Follow naming conventions (lowercase_with_underscores.sh)
  • Keep scripts modular and versioned (Git integration)
  • Use configuration files instead of hardcoded paths
  • Prepare for Module 4 β†’ Variables, I/O & Flow Control

Would you like me to format this into your standard learning-material template (with sections like What You Will Learn, 5W+1H Framework, Core Commands, Expected Output, Quick Lab, Cheat Sheet, etc.) next?​

4. Variables & Parameters​

4.1. Variable Declaration & Fundamentals​

  • 4.1.1 Introduction to Variables
  • What are variables and why they matter in Bash automation.
  • Difference between user-defined, environment, and positional variables.
  • 4.1.2 Declaration Rules
  • Syntax: name=value (no spaces).
  • Quoting values with spaces.
  • Scope: local vs global variables.
  • Reassignment and overwriting.
  • 4.1.3 Referencing Variables
  • Using $variable and ${variable}.
  • Echo and print for output verification.
  • Debugging undeclared or empty variables.

4.2. Environment Variables​

  • Environment Variables
  • Understanding predefined system variables ($PATH, $HOME, $USER, $SHELL).
  • Creating custom environment variables with export.
  • Difference between temporary (session) and persistent (profile) variables.
  • Viewing all environment variables with printenv or env.
  • Unsetting variables (unset VAR).
  • Common use cases in WordPress/Linux environments (e.g., defining $WP_PATH, $BACKUP_DIR).

4.3. Positional Parameters​

  • Positional Parameters
  • Definition and use in scripts for handling user input.
  • Access syntax: $1, $2, $3, $@, $#.
  • Quoting $@ vs $* (difference in multi-word arguments).
  • Checking argument count ($#) and conditional execution.
  • Real-world examples: parameterized backup or deployment scripts.

4.4. Special Variables​

  • Special Variables
  • $? β†’ Exit status of the last command.
  • $$ β†’ Current process ID (useful for logs and temp files).
  • $! β†’ PID of the last background process.
  • $UID β†’ Current user’s ID (for permission checks).
  • $RANDOM β†’ Generate pseudo-random numbers.
  • Practical Applications
  • Create process-aware scripts.
  • Generate unique filenames using PIDs or timestamps.
  • Use $? for conditional error handling and logging.

4.5. Parameter Expansion​

  • Parameter Expansion
  • Basic substitution: ${var} and default values ${var:-default}.
  • String manipulation:
  • Replace: ${var/old/new} or ${var//old/new}
  • Remove prefix/suffix: ${var#pattern}, ${var%pattern}
  • Length of variable: ${#var}
  • Safe expansion and null handling.
  • Real-world automation uses: filename trimming, path normalization, log sanitization.
  • Debugging malformed expansions.

4.6. Hands-On Labs​

  • Create and export variables across sessions.
  • Build parameterized scripts (accepting input via $1, $2, etc.).
  • Test all special variables ($?, $RANDOM, etc.) in live CLI.
  • Use parameter expansion for dynamic filename handling.

4.7. Best Practices & Next Steps​

  • Prefer meaningful variable names (backup_path, db_user).
  • Quote all variable references to avoid word-splitting errors.
  • Use uppercase for environment variables, lowercase for local ones.
  • Use set -u or set -o nounset to detect uninitialized variables.
  • Prepare for Module 5 β†’ Input, Output & Redirection (I/O management for automation).


5. Input, Output & Redirection​

5.1. Standard Streams​

  • 5.1.1 Understanding Stream Architecture
  • The three standard data streams in Linux:
  • stdin (0) β†’ standard input
  • stdout (1) β†’ standard output
  • stderr (2) β†’ standard error
  • How processes communicate using streams.
  • Viewing stream flow in a shell process diagram.
  • 5.1.2 Practical Exploration
  • Use cat, echo, and grep to visualize stream input/output.
  • Redirect errors vs normal output to observe their separation.
  • WordPress/VPS example: monitor logs and error messages from CLI tools.

5.2. Redirection Operators​

  • 5.2.1 Output Redirection
  • > β†’ redirect output (overwrite).
  • >> β†’ append output to file.
  • 2> β†’ redirect error stream.
  • &> β†’ redirect both stdout and stderr.
  • Examples:
  • ls > list.txt β†’ save output to file.
  • wp plugin update all > log.txt 2>&1 β†’ redirect both output and error.
  • 5.2.2 Input Redirection
  • < β†’ use file as input source.
  • Combining input/output redirection in one command.
  • 5.2.3 File Descriptor Numbers
  • Understanding 0, 1, 2 and their meaning.
  • Advanced case: redirecting specific streams in long scripts.
  • 5.2.4 Troubleshooting
  • Handling permission errors (Permission denied).
  • Preventing overwrites using set -o noclobber.

5.3. Piping (|)​

  • 5.3.1 Concept of Command Chaining via Piping
  • Definition and how | connects stdout of one command to stdin of another.
  • Syntax: cmd1 | cmd2
  • Comparison between piping and redirection.
  • 5.3.2 Practical Examples
  • cat access.log | grep "404" β†’ filter error lines.
  • ps aux | grep nginx | wc -l β†’ count running processes.
  • df -h | tee storage_report.txt β†’ view and save simultaneously.
  • Multi-stage pipeline (cmd1 | cmd2 | cmd3).
  • 5.3.3 Advanced: Pipe Failures
  • Using set -o pipefail to capture failure exit codes.

5.4. Tee Command​

  • **5.4.1 Introduction to **tee
  • Purpose: read from stdin, write to stdout and file at once.
  • Syntax: command | tee file
  • 5.4.2 Common Use Cases
  • Logging command output while monitoring it in real-time.
  • Combining with sudo: sudo tee /etc/config.conf.
  • Example: wp plugin list | tee wp-plugins.txt
  • 5.4.3 Flags and Options
  • a β†’ append mode.
  • i β†’ ignore interrupts.
  • Piping tee with grep or awk for filtered logging.

5.5. Here Documents & Here Strings​

  • 5.5.1 Here Documents (<<)
  • Multi-line input redirection directly in script.
  • Syntax:
cat <<EOF
Line 1
Line 2
EOF

  • Typical uses: generating config files or SQL queries inline.
  • 5.5.2 Here Strings (<<<)
  • Single-line inline input:
grep "root" <<< "root:x:0:0:root:/root:/bin/bash"

  • Difference between << and <<<.
  • Practical use: feeding test data without external files.
  • 5.5.3 WordPress/Linux Examples
  • Use <<EOF to create wp-config templates dynamically.
  • Automate Nginx/OLS config creation through inline heredocs.

5.6. Hands-On Labs​

  • Redirect and append command outputs to different files.
  • Combine redirection and piping in multi-step processes.
  • Use tee to log results while executing real-time tasks.
  • Write a Bash script that generates and writes configuration files using heredocs.
  • Debug script outputs using stream redirection.

5.7. Best Practices & Next Steps​

  • Always handle stderr explicitly when logging automation.
  • Prefer tee for transparency during automation runs.
  • Use set -o pipefail for safer pipelines.
  • Keep output logs timestamped for debugging.
  • Prepare for Module 6 β†’ Conditional Logic & Flow Control (building decision-based automation scripts).


6. Conditional Logic & Flow Control​

6.1. If / Else Structures​

  • 6.1.1 Fundamentals of Conditional Execution
  • What conditional branching means in automation.
  • When and why to use if, elif, and else in Bash.
  • 6.1.2 Syntax & Examples
if [ condition ]; then
commands
elif [ other_condition ]; then
commands
else
commands
fi

  • Difference between single brackets [ ], double brackets [[ ]], and test command.
  • Using logical operators (&&, ||) inside conditions.
  • Example: Check if a WordPress directory exists before backup or update.
  • 6.1.3 Common Mistakes & Debugging
  • Missing spaces around brackets.
  • Improper use of quotes with variables.
  • Debugging condition flow using set -x.

6.2. Comparison Operators​

  • 6.2.1 Numeric Comparisons
  • eq, ne, lt, le, gt, ge
  • Example: Verify CPU load, memory usage, or file count.
  • 6.2.2 String Comparisons
  • ==, !=, <, > inside [[ ]]
  • z (empty string), n (non-empty string).
  • Example: Validate username or input string from user.
  • 6.2.3 Logical Combinations
  • && (AND), || (OR) inside conditions.
  • Grouping with parentheses for complex logic.
  • 6.2.4 Real-World Example
if [[ "$ENV" == "production" && -f "wp-config.php" ]]; then
echo "Deploying live site..."
fi


6.3. File & Directory Tests​

  • 6.3.1 Understanding File Test Operators
  • f β†’ True if file exists and is regular.
  • d β†’ True if directory exists.
  • r, w, x β†’ Read, write, execute permissions.
  • s β†’ File exists and is not empty.
  • e β†’ File or directory exists.
  • 6.3.2 Combined Tests
  • Example:
if [ -d "/var/www/html" ] && [ -w "/var/www/html" ]; then
echo "Writable directory found."
fi

  • Combining file checks with conditional branching.
  • 6.3.3 Troubleshooting File Tests
  • Understanding symbolic links (L).
  • Handling permission-denied errors gracefully.

6.4. Case Statements​

  • 6.4.1 Introduction & Syntax
  • Simplify multi-branch logic using case ... esac.
case $variable in
start)
systemctl start nginx;;
stop)
systemctl stop nginx;;
restart)
systemctl restart nginx;;
*)
echo "Usage: $0 {start|stop|restart}";;
esac

  • 6.4.2 When to Use Case Instead of If
  • For menu-driven scripts or multiple discrete values.
  • Easier readability and maintenance.
  • 6.4.3 Advanced Case Features
  • Pattern matching with wildcards (.log, [yY]es).
  • Nested cases and fall-through handling.

6.5. Exit Control & Loop Flow Management​

  • 6.5.1 Exit and Return Control
  • exit β†’ terminate script with a status code.
  • return β†’ exit a function, not the whole script.
  • Use of exit codes for automation health checks.
  • 6.5.2 Loop Flow Modifiers
  • break β†’ stop the current loop.
  • continue β†’ skip current iteration and proceed to next.
  • Example:
for file in *.log; do
[[ ! -s $file ]] && continue
echo "Processing $file..."
done

  • 6.5.3 Practical Automation Cases
  • Auto-retry failed tasks using exit codes.
  • Stop workflows safely using controlled exits.

6.6. Hands-On Labs​

  • Create a Bash script that checks system resource usage and reacts accordingly.
  • Build menu-driven maintenance tools using case.
  • Automate backup validation using file test operators.
  • Experiment with loops and conditional exit logic.
  • Use nested if and case statements to simulate real deployment logic.

6.7. Best Practices & Next Steps​

  • Keep conditions clear and readable (avoid deep nesting).
  • Always quote variables to prevent word-splitting errors.
  • Use double brackets [[ ]] for safety and better syntax.
  • Return proper exit codes (0 for success, non-zero for errors).
  • Prepare for Module 7 β†’ Loops & Iteration (automating repetitive workflows).

7. Loops & Iteration​

7.1. For Loops​

  • 7.1.1 Introduction to Iteration
  • What loops are and why they’re essential in Bash automation.
  • Typical use cases: iterating files, users, or WordPress sites in a VPS.
  • 7.1.2 Syntax Variants
for var in list; do
commands
done

  • Looping over strings, numbers, or command substitution results.
  • Example:
for site in /var/www/*; do
echo "Checking $site"
done

  • 7.1.3 C-Style Loops
for ((i=1; i<=5; i++)); do
echo "Run #$i"
done

  • Comparison to traditional shell for-loops.
  • Numeric control and performance considerations.
  • 7.1.4 Advanced: Arrays and File Lists
  • Iterating through arrays:
arr=(wp1 wp2 wp3)
for site in "${arr[@]}"; do
echo "Updating $site"
done

  • Combining find or ls output with loops for batch automation.

7.2. While & Until Loops​

  • 7.2.1 While Loops
while [ condition ]; do
commands
done

  • Executes as long as condition is true.
  • Example: monitor system uptime or service status.
  • 7.2.2 Until Loops
until [ condition ]; do
commands
done

  • Executes until condition becomes true (opposite of while).
  • Example: retry loop until network or database is reachable.
  • 7.2.3 Infinite Loops & Safe Exits
  • Creating deliberate infinite loops (while :; do ... done).
  • Breaking safely with conditions or signals.

7.3. Loop Control​

  • 7.3.1 Flow Management
  • break β†’ terminate current loop.
  • continue β†’ skip current iteration and continue.
  • Example:
for file in *.log; do
[[ ! -s $file ]] && continue
echo "Processing $file..."
done

  • 7.3.2 Nested Control
  • Exiting outer loops using labels (break 2).
  • Skipping specific iterations in nested structures.
  • 7.3.3 Error Handling Inside Loops
  • Check $? for previous command failures.
  • Gracefully exit loops on unexpected states.

7.4. Nested Loops​

  • 7.4.1 Concept and Use Cases
  • Using a loop inside another to handle matrix-style data or directory traversal.
  • Syntax pattern:
for dir in */; do
for file in "$dir"*.log; do
echo "$file"
done
done

  • 7.4.2 Real-World Scenarios
  • WordPress multisite operations (looping through sites, then plugins).
  • Database backup per site inside parent iteration.
  • 7.4.3 Performance Optimization
  • Avoid unnecessary nesting; prefer command substitution when possible.
  • Log iteration progress for visibility.

7.5. Practical Use Cases​

  • 7.5.1 System Administration Automation
  • Periodic cleanup of temp/log files.
  • Batch updates or plugin audits across multiple installations.
  • Resource monitoring loops that alert based on thresholds.
  • 7.5.2 File & Directory Management
  • Renaming files in bulk with for.
  • Iterating with while read to process file lines.
  • 7.5.3 Integration with External Tools
  • Combining loops with cron or systemd for scheduled automation.
  • Incorporating conditional checks and error trapping for robust workflows.

7.6. Hands-On Labs​

  • Build a script that loops through all /var/www directories to check disk usage.
  • Create a while loop that pings a server until it responds.
  • Implement nested loops for multi-site WordPress plugin updates.
  • Use break and continue to handle different file conditions.
  • Add error-handling logic that stops the loop after multiple failures.

7.7. Best Practices & Next Steps​

  • Always include exit conditions to prevent infinite loops.
  • Quote all variables in loops to avoid globbing issues.
  • Use meaningful variable names like site, dir, file, index.
  • Combine set -e and trap for safer automated iterations.
  • Prepare for Module 8 β†’ Functions & Modular Scripting (reusing logic for cleaner automation).

8. Functions & Modularity​

8.1. Declaring Functions​

  • 8.1.1 Introduction to Functions
  • What functions are and why they matter in scripting.
  • Benefits: reusability, clarity, and reduced redundancy in Bash automation.
  • 8.1.2 Syntax Variants
function_name() {
commands
}

or

function function_name {
commands
}

  • When to use function keyword and when not.
  • Function naming conventions and readability tips.
  • 8.1.3 Execution Flow
  • Defining vs invoking functions.
  • Script load order β€” functions must be defined before being called.
  • 8.1.4 Practical Example
backup_wp() {
wp db export /backup/db.sql
wp plugin update --all
}
backup_wp

  • Example: reusable backup routine for multiple WordPress sites.

8.2. Function Arguments​

  • 8.2.1 Passing Parameters
  • Use $1, $2, $@, $# inside functions to handle inputs.
greet() {
echo "Hello, $1!"
}
greet Donny

  • 8.2.2 Handling Multiple Arguments
  • Iterating through $@ and $*.
  • Differences between $@ and $* when quoted.
  • 8.2.3 Validating Inputs
  • Check argument count using $#.
  • Display usage/help messages dynamically.
  • 8.2.4 Real-World Example
  • Function for parameterized deployment:
deploy_site() {
local domain=$1
local branch=$2
git -C "/var/www/$domain" pull origin "$branch"
}
deploy_site wpstrategist.com main


8.3. Local Variables​

  • 8.3.1 Understanding Scope
  • Global vs local variable behavior.
  • Why using local prevents variable pollution in large scripts.
  • 8.3.2 Syntax
my_func() {
local var="temp"
echo "$var"
}
echo "$var" # Empty outside function

  • 8.3.3 Best Practices
  • Use local for all function internals.
  • Avoid global variables in shared modules.
  • Example: safe variable handling in multi-function automation scripts.

8.4. Return Values​

  • 8.4.1 Return vs Echo
  • return sends an exit code, not text output.
  • Use echo or printf for text; return for logic control.
  • 8.4.2 Using Exit Codes
check_config() {
[[ -f "/etc/nginx/nginx.conf" ]] && return 0 || return 1
}
if check_config; then
echo "Config exists"
else
echo "Missing configuration"
fi

  • 8.4.3 Capturing Output
  • Assign function results to variables:
result=$(get_version)
echo "$result"

  • 8.4.4 Error Handling
  • Use set -e and trap to catch non-zero returns.
  • Implement centralized error-logging functions.

8.5. Sourcing & Modularity​

  • 8.5.1 Purpose of Sourcing
  • Reuse shared functions without duplicating code.
  • Syntax:
source ./utils.sh
# or
. ./utils.sh

  • 8.5.2 Structuring Modular Scripts
  • Split logic into multiple files:
  • functions.sh β†’ common utilities
  • backup.sh β†’ task-specific logic
  • main.sh β†’ orchestrator script
  • 8.5.3 Environment Awareness
  • Using relative vs absolute paths when sourcing.
  • Prevent sourcing loops with guards ([[ ${FUNC_LOADED:-0} -eq 1 ]] && return).
  • 8.5.4 WordPress/VPS Example
  • common.sh containing generic functions like log_message, check_disk, and reused across all server maintenance scripts.

8.6. Hands-On Labs​

  • Create a modular backup.sh that imports shared functions.
  • Build functions that accept parameters and validate input.
  • Practice isolating variables with local.
  • Capture and interpret return codes from different function outcomes.
  • Modularize your WordPress deployment workflow into multiple source files.

8.7. Best Practices & Next Steps​

  • Define functions before use for clarity.
  • Use local for safety and readability.
  • Return codes for automation logic; echo only for user output.
  • Keep shared functions in version-controlled repositories.

9. String & Text Operations​

9.1. String Manipulation​

  • 9.1.1 Introduction to String Operations
  • Why text handling is critical in Bash scripting (e.g., parsing config files, logs, CLI arguments).
  • Difference between plain text and variable strings.
  • 9.1.2 Basic Operations
  • Concatenation: full="$first $last".
  • Length of string: ${#var}.
  • Substring extraction: ${var:position:length}.
  • Example:
domain="wpstrategist.com"
echo "${domain:0:12}" # Output: wpstrategist

  • 9.1.3 Advanced Editing
  • Removing whitespace, trimming, or splitting lines.
  • Using cut, awk, and sed for structured manipulation.
  • Example: extract username from /etc/passwd or domain from URL.

9.2. Pattern Matching​

  • 9.2.1 Wildcards in Bash
  • β†’ matches any number of characters.
  • ? β†’ matches a single character.
  • [a-z] β†’ matches character ranges.
  • Example:
for file in *.log; do
echo "Found $file"
done

  • **9.2.2 Regex Matching with **=~
  • Using extended patterns inside [[ ]]:
if [[ "[email protected]" =~ ^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$ ]]; then
echo "Valid email"
fi

  • Use cases: validation, text classification, pattern extraction.
  • 9.2.3 Real-World Automation Scenarios
  • Validate file naming conventions before deployment.
  • Identify log lines matching specific keywords or timestamps.

9.3. Parameter Substitution​

  • 9.3.1 Overview of Expansion Patterns
  • ${var#pattern} β†’ remove shortest prefix.
  • ${var##pattern} β†’ remove longest prefix.
  • ${var%pattern} β†’ remove shortest suffix.
  • ${var%%pattern} β†’ remove longest suffix.
  • ${var//old/new} β†’ replace all occurrences.
  • 9.3.2 Examples
path="/var/www/html/wp-config.php"
echo "${path##*/}" # wp-config.php
echo "${path%/*}" # /var/www/html

  • 9.3.3 Practical Use Cases
  • Dynamic filename or URL extraction.
  • WordPress path cleanup before backup or sync operations.
  • Batch renaming using pattern substitution.

9.4. String Comparison​

  • 9.4.1 Equality & Inequality
  • == β†’ equal strings.
  • != β†’ not equal.
  • Example:
if [[ "$ENV" == "production" ]]; then
echo "Deploying live"
fi

  • 9.4.2 Empty & Non-Empty Tests
  • z "$var" β†’ true if variable is empty.
  • n "$var" β†’ true if variable is not empty.
  • Useful for validating inputs or config states.
  • 9.4.3 Lexicographical Comparison
  • Compare alphabetic order using < or > inside [[ ]].
  • Example:
[[ "abc" < "abd" ]] && echo "abc comes first"

  • 9.4.4 Error Handling
  • Always quote strings to prevent word-splitting and globbing errors.

9.5. Case Conversion​

  • 9.5.1 Built-In Case Transformations
  • ${var^^} β†’ uppercase entire string.
  • ${var,,} β†’ lowercase entire string.
  • ${var^} β†’ capitalize first letter.
  • ${var,} β†’ lowercase first letter.
  • Example:
name="wordpress"
echo "${name^^}" # WORDPRESS
echo "${name^}" # Wordpress

  • 9.5.2 Combining Case Conversion with Other Operations
  • Clean and normalize user input before processing.
  • Convert filenames or slugs for SEO-friendly output.
  • 9.5.3 Practical Scenarios
  • Normalize domain names or user IDs.
  • Standardize log formats in scripts.

9.6. Hands-On Labs​

  • Extract sub-strings from system paths or URLs.
  • Build a script to validate email or domain patterns using regex.
  • Practice text cleanup using ${var//} expansions.
  • Create a text converter that uppercases and trims inputs.
  • Combine awk, grep, and Bash expansions for complex text processing.

9.7. Best Practices & Next Steps​

  • Always quote strings in conditions to avoid misinterpretation.
  • Prefer Bash parameter expansion over external tools for speed.
  • Use regex only when wildcard matching isn’t sufficient.
  • Keep patterns readable and documented for future maintenance.
  • Prepare for Module 10 β†’ Arrays & Data Structures, where string lists evolve into structured collections for advanced automation.

10. File & Directory Operations​

10.1. File Tests​

  • 10.1.1 Introduction to File Testing
  • Purpose: verifying file and directory states before performing actions.
  • Importance in automation to prevent accidental deletions or overwrites.
  • 10.1.2 Core Test Operators
OperatorMeaningExample
-eFile or directory exists[ -e file.txt ]
-fRegular file exists[ -f script.sh ]
-dDirectory exists[ -d /var/www/html ]
-rRead permission[ -r config.php ]
-wWrite permission[ -w log.txt ]
-xExecutable[ -x deploy.sh ]
-sNon-empty file[ -s wp-config.php ]
  • 10.1.3 Practical Usage
if [ -d /var/www/html ]; then
echo "Directory exists"
else
echo "Missing directory"
fi

  • Combine multiple checks using && or ||.
  • Use in deployment, backup, or monitoring scripts.

10.2. Create & Remove​

  • 10.2.1 File Creation
  • touch file.txt β†’ create empty file or update timestamp.
  • Auto-create logs or temp files during automation.
  • 10.2.2 Directory Creation
  • mkdir dirname β†’ create directory.
  • mkdir -p /path/to/subdir β†’ create parent directories automatically.
  • 10.2.3 File & Directory Removal
  • rm file.txt β†’ delete file.
  • rm -r directory β†’ recursive delete.
  • rm -rf β†’ force delete (use cautiously).
  • 10.2.4 Real-World Example
mkdir -p /backup/$(date +%F)
touch /backup/$(date +%F)/status.log

  • Automate creation of daily backup folders.

10.3. Copy & Move​

  • 10.3.1 Copying Files
  • cp source destination β†’ copy single file.
  • cp -r src_dir dest_dir β†’ recursive copy.
  • cp -u β†’ copy only if source is newer.
  • 10.3.2 Moving or Renaming
  • mv old.txt new.txt β†’ rename file.
  • mv file /target/path/ β†’ move to directory.
  • Example:
mv *.log /var/log/archive/

  • 10.3.3 Combined Operations
  • Integrate with condition checks (if [ -f ]) for safe file handling.
  • Real-world: move logs older than 7 days, copy site configs before update.

  • 10.4.1 What Are Symbolic Links
  • Shortcut-style references to other files or directories.
  • Difference between hard links and symbolic links.
  • 10.4.2 Syntax
  • ln -s target link_name
  • Example:
ln -s /var/www/html/wp-config.php /root/config-link

  • 10.4.3 Managing Links
  • View links: ls -l.
  • Remove link: rm link_name.
  • Update broken links automatically with scripts.
  • 10.4.4 Real-World Application
  • Commonly used for shared config files or staging-production symlink switching.

10.5. Path Operations​

  • 10.5.1 Working with Paths
  • basename /path/to/file β†’ extract filename.
  • dirname /path/to/file β†’ extract directory name.
  • realpath relative/path β†’ get absolute path.
  • 10.5.2 Practical Examples
file="/var/www/html/wp-config.php"
echo "File: $(basename $file)"
echo "Dir: $(dirname $file)"
echo "Full: $(realpath $file)"

  • 10.5.3 Use Cases
  • Simplify logs by extracting only filenames.
  • Combine with loops to dynamically handle WordPress installations.
  • Use realpath to resolve symlink paths in backup scripts.

10.6. Hands-On Labs​

  • Test file existence and permission before performing actions.
  • Create, move, and delete directories for project workflows.
  • Write a script that copies logs to a timestamped folder.
  • Build a symlink manager for configuration files.
  • Use basename and dirname to parse file paths dynamically.

10.7. Best Practices & Next Steps​

  • Always verify existence before modifying or deleting files.
  • Avoid using rm -rf without double confirmation or dry-run option.
  • Use relative paths for portability, realpath for precision.
  • Keep automated file operations logged for recovery.
  • Prepare for Module 11 β†’ Input Handling & User Interaction, focusing on user prompts, reading input safely, and dynamic script behavior.

11. Archiving & Compression (Bash Native)
​

**11.1. Using **tar​

  • 11.1.1 Introduction to Archiving
  • Purpose: combining multiple files/directories into a single archive.
  • Common use cases: backups, deployments, and transfers.
  • Difference between archiving (tar) and compression (gzip, zip).
  • 11.1.2 Core Syntax
CommandPurposeExample
tar -cvf archive.tar file1 file2Create archivetar -cvf backup.tar /var/www/html
tar -xvf archive.tarExtract archivetar -xvf backup.tar -C /restore
tar -tvf archive.tarList contents
  • Flags:
  • c β†’ create
  • x β†’ extract
  • t β†’ list
  • v β†’ verbose
  • f β†’ specify file
  • 11.1.3 Advanced Usage
  • Exclude files: tar --exclude='*.log' -cvf backup.tar /var/www/html
  • Append to archive: tar -rvf archive.tar newfile.txt
  • Combine with compression: tar -czvf backup.tar.gz /path
  • 11.1.4 WordPress/VPS Examples
  • Full /var/www backup for all sites.
  • Extract archives for migration or restore tasks.

11.2. Gzip & Gunzip​

  • 11.2.1 Purpose & Use Cases
  • Compress single files for faster transfer and reduced storage.
  • Common in log rotation and backups.
  • 11.2.2 Syntax
CommandDescriptionExample
gzip file.txtCompress file
gzip -k file.txtKeep original file
gunzip file.txt.gzDecompress file
  • 11.2.3 Flags & Variations
  • v β†’ show compression ratio.
  • r β†’ compress recursively.
  • t β†’ test compressed file integrity.
  • 11.2.4 Real-World Scenarios
  • Compress logs after rotation:
gzip /var/log/nginx/access.log

  • Automatically decompress backup archives before restore.

11.3. Zip & Unzip​

  • **11.3.1 Difference Between tar and **zip
  • zip compresses per file; tar bundles before compression.
  • zip archives are cross-platform friendly (Windows/Linux).
  • 11.3.2 Syntax
CommandDescriptionExample
zip archive.zip file1 file2Create ZIP file
unzip archive.zipExtract files
zip -r site.zip /var/www/htmlRecursive directory zip
  • 11.3.3 Useful Flags
  • r β†’ include subdirectories.
  • q β†’ quiet mode.
  • d β†’ remove entries from archive.
  • 11.3.4 WordPress Automation
  • Package plugin or theme folders for version deployment.
  • Compress backups for offsite sync.

11.4. Combine Commands (Pipelines)​

  • 11.4.1 Chaining with Pipes
  • Stream data between commands:
tar -czf - /var/www | gzip > backup.tar.gz

  • Combine with SSH:
tar -czf - /var/www | ssh user@server "cat > backup.tar.gz"

  • 11.4.2 Parallel Compression Workflows
  • Use pipes for on-the-fly archiving without temp files.
  • Example: compress + transfer in one step.
  • 11.4.3 Automation in Scripts
  • Chain commands using && or | for error-safe workflows.
  • Integrate with cron jobs for periodic backups.

11.5. File Integrity & Validation​

  • 11.5.1 Exit Codes & Verification
  • Check command success via $?:
tar -czf backup.tar.gz /var/www
if [ $? -eq 0 ]; then
echo "Backup successful"
else
echo "Backup failed"
fi

  • Use tar -tzf or gzip -t to verify archive integrity.
  • 11.5.2 Checksums for Validation
  • Generate checksum: sha256sum backup.tar.gz > backup.sha256
  • Verify checksum: sha256sum -c backup.sha256
  • 11.5.3 Logging Archive Results
  • Write success/failure to log files for automation reports.

11.6. Hands-On Labs​

  • Create and extract tar archives with various flags.
  • Compress and decompress log files using gzip and zip.
  • Build a pipeline that creates and transfers an archive in one line.
  • Validate backups using checksum comparison.
  • Automate archive creation in a daily cron job with logging.

11.7. Best Practices & Next Steps​

  • Use descriptive archive names with timestamps (backup_$(date +%F).tar.gz).
  • Always verify exit codes before deleting original files.
  • Avoid compressing already-compressed formats (e.g., .jpg, .zip).
  • Maintain checksum logs for integrity tracking.
  • Prepare for Module 12 β†’ Process Management & Job Control, where you’ll handle background tasks, monitoring, and execution flow.

12. Error Handling & Debugging​

12.1. Exit Status​

  • 12.1.1 Introduction to Exit Codes
  • Every command returns an exit status β€” 0 for success, non-zero for failure.
  • Purpose: detect and respond to errors in automation scripts.
  • 12.1.2 Checking Exit Codes
cp file1.txt /backup/
if [ $? -eq 0 ]; then
echo "Copy successful"
else
echo "Copy failed"
fi

  • $? captures the exit status of the most recent command.
  • Common codes:
CodeMeaningExample
0SuccessCommand completed normally
1General errorInvalid argument
2Misuse of shell builtinsSyntax error
127Command not foundTypo in command name
130Script terminated by Ctrl+CSIGINT interrupt
  • 12.1.3 Use in Scripts
  • Branch workflows based on success/failure.
  • Stop execution for critical steps (e.g., database export failures).

12.2. Error Redirection​

  • 12.2.1 Understanding Streams
  • stdout (1) β†’ normal output
  • stderr (2) β†’ error messages
  • 12.2.2 Redirection Syntax
CommandDescription
command 2> error.logRedirect errors to file
command &> all.logRedirect both stdout and stderr
command 2>> error.logAppend errors to existing file
  • 12.2.3 Combined Example
tar -czf backup.tar.gz /var/www 2>error.log
echo $? >> backup_status.log

  • Separate logs for output and errors for clarity.
  • 12.2.4 Practical Usage
  • Capture WP-CLI errors during plugin updates.
  • Combine with tee for real-time monitoring and logging.

12.3. Traps & Signals​

  • 12.3.1 What Are Signals
  • Signals are OS-level interrupts like SIGINT (Ctrl+C) or SIGTERM (kill).
  • Used to manage script termination gracefully.
  • **12.3.2 Using **trap
trap 'echo "Cleanup in progress..."; rm -f /tmp/tempfile' SIGINT SIGTERM

  • Execute custom cleanup code when a signal is received.
  • 12.3.3 Common Signals
SignalDescription
SIGINTUser interrupt (Ctrl+C)
SIGTERMTermination signal
SIGQUITQuit signal
EXITTriggered when script finishes
  • 12.3.4 Real-World Application
  • Cleanup temporary files.
  • Stop background processes safely.
  • Log interruption events for monitoring.

12.4. Debug Options​

  • 12.4.1 Enabling Debug Mode
  • set -x β†’ trace command execution step-by-step.
  • set +x β†’ disable tracing.
  • Example:
set -x
cp /nonexistent /tmp/
set +x

  • 12.4.2 Error Exit Mode
  • set -e β†’ stop script on first command failure.
  • Combine with set -u (treat unset variables as errors).
  • Example:
set -euo pipefail

  • Recommended for production-grade automation.
  • 12.4.3 Dry-Run and Logging
  • Use echo for safe previews of commands.
  • Combine tracing with log files for debugging sessions.
  • 12.4.4 Integration Example
set -e
wp plugin update --all || echo "Plugin update failed" >> error.log


12.5. Safe Execution​

  • 12.5.1 Combining Error Handling Mechanisms
  • Use set -e + trap + redirection for robust scripts.
  • Example:
#!/bin/bash
set -e
trap 'echo "Aborted at line $LINENO"; exit 1' ERR
tar -czf /backup/site.tar.gz /var/www
echo "Backup complete"

  • **12.5.2 Using **pipefail
  • Ensures pipelines fail when any command fails.
  • Example:
set -o pipefail
grep "error" access.log | sort | uniq > errors.txt

  • 12.5.3 Logging for Automation
  • Append both success and failure results to a unified log.
  • Timestamp each operation for post-run review.
  • 12.5.4 Real-World Automation Example
  • Safe backup routine with error recovery and notifications.

12.6. Hands-On Labs​

  • Simulate failures and capture exit codes.
  • Redirect stderr to error log while displaying output on screen.
  • Implement a trap that cleans temporary files when script is interrupted.
  • Enable debug tracing and log it to a file.
  • Build a resilient automation script that combines all techniques.

12.7. Best Practices & Next Steps​

  • Always log both normal and error outputs for traceability.
  • Use set -euo pipefail in production scripts.
  • Clean up temporary files with trap EXIT.
  • Avoid ignoring exit codes β€” always handle errors gracefully.
  • Prepare for Module 13 β†’ Process Management & Job Control, focusing on background processes, subshells, and execution monitoring.

13. Process & Job Control​

13.1. Foreground & Background Jobs​

  • 13.1.1 Introduction to Job Control
  • Bash can manage multiple tasks simultaneously β€” either interactively or in automation.
  • Foreground jobs occupy the terminal; background jobs free it for other tasks.
  • 13.1.2 Starting Background Jobs
  • Append & to run a command in background:
tar -czf backup.tar.gz /var/www &

  • Shell displays a job ID ([1]) and PID.
  • 13.1.3 Managing Foreground & Background Tasks
  • Suspend with Ctrl+Z, resume in background (bg) or foreground (fg).
  • Example workflow:
sleep 300 &
jobs
fg %1

  • 13.1.4 Real-World Use
  • Run long database backups or log processing jobs without blocking terminal access.

13.2. Job Listing & Control​

  • 13.2.1 Viewing Active Jobs
  • jobs β†’ list current background and suspended tasks.
  • Output includes job ID, state, and command.
  • 13.2.2 Bringing Jobs to Foreground
  • fg %1 β†’ bring job 1 back to foreground.
  • 13.2.3 Resuming or Stopping Jobs
  • bg %1 β†’ resume job 1 in background.
  • kill %1 β†’ stop a job by ID.
  • 13.2.4 Practical Usage
  • Manage multiple automated tasks (e.g., log compression, MySQL dumps).
  • Useful for multi-task server management from a single terminal session.

13.3. PID Handling & Process Control​

  • 13.3.1 Understanding Process IDs
  • Each running command is assigned a unique PID.
  • Retrieve PID of last background process with $!.
  • 13.3.2 Monitoring & Controlling Processes
  • ps -ef β†’ view all active processes.
  • kill PID β†’ terminate a process.
  • kill -9 PID β†’ force-kill if unresponsive.
  • wait PID β†’ pause script until process completes.
  • 13.3.3 Example
tar -czf backup.tar.gz /var/www &
pid=$!
wait $pid
echo "Backup process ($pid) completed."

  • 13.3.4 Real-World Application
  • Queue long jobs and wait for completion before triggering dependent actions.

13.4. Subshells​

  • 13.4.1 Definition & Concept
  • Subshells are isolated execution environments within Bash.
  • Created with parentheses ( ).
  • Variables inside subshells don’t affect the parent shell.
  • 13.4.2 Syntax & Examples
(cd /var/www && ls)
echo $PWD # Unchanged

  • Compare with curly braces { } which run in current shell.
  • 13.4.3 Common Use Cases
  • Temporary directory changes.
  • Parallel tasks with backgrounded subshells.
  • Isolating environment variables during automation.
  • 13.4.4 Advanced Pattern
(tar -czf backup.tar.gz /var/www &)
(mysqldump -u root db > db.sql &)
wait
echo "All background subshells done."


13.5. Daemon Scripts​

  • 13.5.1 What Is a Daemon
  • Long-running background service detached from terminal.
  • Commonly used for monitoring, cleanup, or sync scripts.
  • 13.5.2 Creating Simple Daemons
#!/bin/bash
while true; do
rsync -a /var/www /backup
sleep 3600
done &

  • The script keeps running in background at system level.
  • 13.5.3 Process Management
  • Redirect outputs to logs: script.sh > /var/log/script.log 2>&1 &.
  • Use nohup to persist after logout: nohup ./script.sh &.
  • 13.5.4 Integration With System Tools
  • Combine with systemd or cron for automatic startup.
  • Monitor using ps, top, or pgrep.
  • 13.5.5 Real-World Use
  • Implement persistent sync daemons for backups or log collection.

13.6. Hands-On Labs​

  • Start a background process and bring it to foreground.
  • Capture and monitor a PID from a running command.
  • Build a multi-process workflow using subshells and wait.
  • Convert a monitoring loop into a background daemon using nohup.
  • Log process output and validate completion codes.

13.7. Best Practices & Next Steps​

  • Always log PID and outputs for traceability.
  • Avoid leaving orphan background jobs.
  • Combine trap with kill for clean shutdowns.
  • Use wait to synchronize multiple concurrent tasks.
  • Prepare for Module 14 β†’ Scheduling & Automation, where you’ll learn cron jobs, timers, and advanced workflow orchestration.

14. Date & Time Utilities​

14.1. The date Command​

  • 14.1.1 Introduction to Date Handling in Bash
  • Used for retrieving, formatting, and manipulating date/time values.
  • Essential for timestamped backups, logs, and automation.
  • 14.1.2 Core Syntax
CommandDescriptionExample
dateShow current date/timeFri Oct 17 14:22:03 UTC 2025
date +"%Y-%m-%d"Custom format (ISO)2025-10-17
date +"%H:%M:%S"Time only14:22:03
date +"%F_%H-%M-%S"Filename-safe timestamp2025-10-17_14-22-03
  • 14.1.3 Common Format Specifiers
SymbolMeaningExample
%YYear2025
%mMonth (01–12)10
%dDay17
%HHour (00–23)14
%MMinute22
%SSecond03
%FFull date (YYYY-MM-DD)2025-10-17
  • 14.1.4 Real-World Example
backup_file="backup_$(date +%F_%H-%M-%S).tar.gz"
tar -czf /backup/$backup_file /var/www

  • Automatically create unique, timestamped archives.

14.2. Time Arithmetic​

  • **14.2.1 Using **date -d
  • Perform relative or offset-based time calculations. | Command | Description | |----------|-------------| | date -d "yesterday" | Previous day | | date -d "next Monday" | Upcoming Monday | | date -d "+7 days" | Add 7 days | | date -d "-2 hours" | Subtract 2 hours |
  • 14.2.2 Output Customization
echo "Cleanup date: $(date -d '+7 days' +%F)"

  • 14.2.3 Practical Use Cases
  • Schedule cleanup scripts.
  • Generate filenames for logs or backups with retention periods.
  • Automate rotation or expiry logic based on timestamps.

14.3. Sleep & Delay​

  • **14.3.1 Purpose of **sleep
  • Pause execution for a set duration.
  • Syntax: sleep [seconds]
  • 14.3.2 Examples
CommandDescription
sleep 5Pause for 5 seconds
sleep 2mPause for 2 minutes
sleep 1hPause for 1 hour
  • 14.3.3 Real-World Use
  • Delay between retries in automation loops.
  • Stagger process execution to prevent system overload.
  • Example:
echo "Waiting for database..."
sleep 10
echo "Resuming process"

  • 14.3.4 Integration with Condition Checks
  • Combine sleep in retry logic:
until ping -c1 server; do
echo "Retrying..."
sleep 5
done


14.4. Script Timing​

  • 14.4.1 The time Command
  • Measure how long a command or script takes to execute.
  • Syntax: time command
  • Example:
time tar -czf backup.tar.gz /var/www

  • 14.4.2 Understanding Output
FieldMeaning
realTotal wall-clock time
userCPU time in user mode
sysCPU time in kernel mode
  • 14.4.3 Use Cases
  • Benchmark command performance.
  • Identify bottlenecks in backup or deployment scripts.
  • Log performance results for optimization.

14.5. Timestamping & Logging​

  • 14.5.1 Generating Timestamped Filenames
logfile="log_$(date +%F_%H-%M-%S).txt"
echo "Backup completed" >> /var/log/$logfile

  • Ensures logs and backups never overwrite each other.
  • 14.5.2 Adding Timestamps to Script Output
echo "$(date +'%F %T') - Process started"

  • Adds readable time markers to logs.
  • 14.5.3 Real-World Automation
  • Create daily logs:
echo "$(date +%F) Backup started" >> backup_$(date +%F).log

  • Integrate timestamps in cron job reports.
  • 14.5.4 Combining with Archiving
  • Append timestamp to archive and checksum filenames for traceability.

14.6. Hands-On Labs​

  • Display current date in multiple formats.
  • Calculate a date 10 days ahead using date -d.
  • Write a script that sleeps between retries.
  • Measure runtime of an archive creation with time.
  • Create timestamped log and backup files automatically.

14.7. Best Practices & Next Steps​

  • Always use ISO format (%F) for compatibility and sorting.
  • Append timestamps to all logs and backups for traceability.
  • Avoid ambiguous time formats in automation (use UTC where possible).
  • Use relative date arithmetic for scheduling cleanup or retention.
  • Prepare for Module 15 β†’ Scheduling & Automation (Cron & Timers), where you’ll integrate these utilities into recurring system jobs.

15. Scheduling & Automation
​

15.1. Cron Jobs​

  • 15.1.1 Introduction to Task Scheduling
  • Cron automates repetitive jobs like backups, log rotation, or monitoring.
  • Cron daemon runs commands at fixed times, dates, or intervals.
  • 15.1.2 Basic Syntax
* * * * * /path/to/script.sh
| | | | |
| | | | └── Day of week (0–6)
| | | └──── Month (1–12)
| | └────── Day of month (1–31)
| └──────── Hour (0–23)
└────────── Minute (0–59)

  • 15.1.3 Common Scheduling Examples
ScheduleDescriptionExample
0 2 * * *Run daily at 2 AMDatabase backup
*/5 * * * *Every 5 minutesHealth check script
0 */6 * * *Every 6 hoursCache cleanup
  • 15.1.4 Managing Cron Jobs
  • Edit jobs: crontab -e
  • View jobs: crontab -l
  • Remove all: crontab -r
  • 15.1.5 Real-World Example
0 1 * * * /usr/local/bin/backup_wp.sh >> /var/log/backup.log 2>&1

  • Automates nightly WordPress backups with log tracking.

15.2. The at Command​

  • 15.2.1 Purpose
  • Execute one-time tasks at a specific time in the future.
  • Ideal for delayed jobs or maintenance tasks.
  • 15.2.2 Syntax & Examples
CommandDescription
at 10pmRun job at 10 PM today
at now + 2 hoursRun 2 hours from now
at 07:30 AM tomorrowSchedule for next day
  • 15.2.3 Workflow
  • Enter commands interactively after at prompt, press Ctrl+D to save.
  • View queued jobs: atq
  • Remove jobs: atrm [job_id]
  • 15.2.4 Real-World Example
echo "/usr/local/bin/cleanup_tmp.sh" | at now + 1 hour

  • Schedule temporary directory cleanup after system updates.

15.3. Intervals & Loops (Manual Timing)​

  • 15.3.1 Using sleep for Script Timing
  • Add manual intervals without cron.
while true; do
bash /usr/local/bin/monitor_wp.sh
sleep 3600
done

  • Useful for lightweight daemons or background loops.
  • 15.3.2 Controlled Interval Loops
  • Add counters or timestamps for logging:
count=1
while [ $count -le 5 ]; do
echo "Run #$count at $(date)"
sleep 10
((count++))
done

  • 15.3.3 Real-World Application
  • Polling resource usage, checking uptime, or pushing logs periodically.

15.4. Log Redirection​

  • 15.4.1 Capturing Automation Output
  • Redirect logs for later inspection:
/usr/local/bin/backup.sh >> /var/log/backup.log 2>&1

  • 15.4.2 File Management
  • Append (>>) instead of overwrite (>).
  • Rotate logs periodically using logrotate or cron cleanup tasks.
  • 15.4.3 Timestamped Logging
echo "$(date +'%F %T') - Backup complete" >> /var/log/backup.log

  • 15.4.4 Combining Logging & Monitoring
  • Use tee to log and display outputs simultaneously.

15.5. Job Verification & Validation​

  • 15.5.1 Checking Exit Status
  • Combine with exit codes for error detection:
/usr/local/bin/backup.sh
if [ $? -eq 0 ]; then
echo "Backup succeeded"
else
echo "Backup failed"
fi

  • 15.5.2 Email Notifications
  • Cron automatically emails the user if output isn’t redirected.
  • Add MAILTO variable:
  • 15.5.3 Status Verification Commands
CommandPurpose
systemctl status cronCheck cron service health
grep CRON /var/log/syslogView cron activity logs
atqList pending one-time jobs
  • 15.5.4 Real-World Automation Example
  • Backup verification job: log results, check success, send notification if failure detected.

15.6. Hands-On Labs​

  • Create a cron job that runs every day and logs output.
  • Schedule a one-time cleanup using at.
  • Build a looping script that runs periodically without cron.
  • Redirect logs and include timestamps in every entry.
  • Validate automation success with exit codes and logs.

15.7. Best Practices & Next Steps​

  • Always redirect cron outputs to logs for traceability.
  • Use absolute paths in cron jobs to prevent environment issues.
  • Avoid overlapping tasksβ€”use PID locks or condition checks.
  • Regularly verify cron execution with logs or monitoring tools.
  • Prepare for Module 16 β†’ Bash Project: WordPress VPS Automation, where you’ll combine all Bash skills to create a full automation workflow for WordPress servers.

16. Advanced Bash Concepts & Integration​

16.1. Regular Expressions​

  • 16.1.1 Introduction to Pattern Matching
  • Regex enables powerful text validation and filtering directly in Bash.
  • Commonly used for data validation, parsing logs, or matching filenames.
  • 16.1.2 Basic Syntax
if [[ $email =~ ^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$ ]]; then
echo "Valid email"
else
echo "Invalid email"
fi

  • Use [[ string =~ regex ]] for built-in Bash matching.
  • 16.1.3 Key Regex Operators
SymbolDescriptionExample
^Start of string^root
$End of string.sh$
.Any single characterh.t
*Zero or more occurrenceslo*g
+One or more occurrences[0-9]+
[ ]Character class[abc]
  • 16.1.4 Real-World Examples
  • Validate domain names, IP addresses, or emails.
  • Parse WordPress logs for failed logins or HTTP errors.
  • Filter text output from grep or awk using conditional regex.

16.2. Command Substitution​

  • 16.2.1 Concept
  • Capture output from a command and reuse it within another command.
  • Syntax:
today=$(date +%F)
echo "Today is $today"

  • 16.2.2 Legacy vs Modern Syntax
TypeExampleNotes
Backticksdate +%FDeprecated due to nesting issues
$()$(date +%F)Recommended for readability
  • 16.2.3 Nested Substitution
archive="backup_$(hostname)_$(date +%F).tar.gz"

  • Combine multiple commands into one inline expression.
  • 16.2.4 Real-World Uses
  • Generate dynamic filenames, hostnames, or timestamps.
  • Capture disk space or process info inside variables.
  • Use with grep or awk to assign filtered results to variables.

16.3. Parallel Execution​

  • 16.3.1 Concept Overview
  • Run multiple independent tasks at once to improve performance.
  • Ideal for heavy I/O or compute operations (e.g., backups, updates).
  • 16.3.2 Running Jobs in Parallel
(tar -czf backup1.tar.gz /site1 &)
(tar -czf backup2.tar.gz /site2 &)
wait
echo "All backups complete"

  • 16.3.3 Managing Parallel Tasks
  • Use background & and wait for synchronization.
  • Control concurrency by batching with loops.
  • 16.3.4 Real-World Example
  • Run multiple site updates simultaneously with WP-CLI.
  • Combine with subshells for safe, isolated execution environments.

16.4. Arrays & Associative Arrays​

  • 16.4.1 Standard Arrays
  • Syntax:
sites=(wpstrategist rezriz metaxenith)
echo "${sites[1]}" # rezriz

  • Iterate through arrays:
for site in "${sites[@]}"; do
echo "Deploying $site"
done

  • 16.4.2 Associative Arrays
  • Store key-value pairs (requires Bash 4+).
declare -A wp_paths=(
["wpstrategist"]="/var/www/wpstrategist"
["rezriz"]="/var/www/rezriz"
)
echo "${wp_paths[wpstrategist]}"

  • 16.4.3 Array Operations
TaskCommandExample
Add itemarray+=(item)sites+=(balancesheet.pro)
List keys${!assoc[@]}
List values${assoc[@]}
Length${#array[@]}
  • 16.4.4 Real-World Uses
  • Manage WordPress site lists and directories.
  • Store configuration mappings (domain β†’ path).
  • Automate deployment or backup operations across multiple environments.

16.5. Script Optimization​

  • 16.5.1 Performance-Oriented Bash Design
  • Avoid redundant loops and repeated calls.
  • Use functions to modularize logic.
  • Pre-check conditions to skip unnecessary operations.
  • 16.5.2 Lazy Evaluation
  • Execute code only when required using short-circuit logic:
[ -f file.txt ] && echo "Exists" || echo "Missing"

  • Prevent resource-heavy commands when conditions fail early.
  • 16.5.3 Modularization
  • Source external function files for cleaner architecture:
source /usr/local/bin/utils.sh

  • Reuse components (logging, backups, monitoring).
  • 16.5.4 Real-World Scenarios
  • Optimize multi-site management scripts.
  • Reduce runtime in loops using arrays and parallelization.
  • Centralize shared logic for consistency across automation scripts.

16.6. Hands-On Labs​

  • Build regex-based input validation scripts.
  • Use command substitution to name log files dynamically.
  • Execute multiple tasks in parallel with & and wait.
  • Create and iterate through associative arrays of WordPress sites.
  • Refactor a long script into modular functions for optimization.

16.7. Best Practices & Next Steps​

  • Always quote variables when using regex or substitution.
  • Use wait to synchronize background jobs before proceeding.
  • Prefer $() over backticks for clarity.
  • Keep functions modular, and maintain reusable function libraries.
  • Prepare for Module 17 β†’ Bash Project Integration: WordPress Automation Suite, where all advanced Bash concepts will merge into a complete automation framework for your WordPress VPS ecosystem.