π 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β
- Intro Quoting & Escaping
- ββ¦.β - Single quotes
- ββ¦.β - Double Quotes
- \ - Backslash
- $ββ¦β - ANSI-C Quoting
- $ββ¦.β - Locale Specific Quoting
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 interpreterissues - Using
envfor 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,
envcommand) - 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
atcommand 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
.shscript - 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
$variableand${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
printenvorenv. - 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 -uorset -o nounsetto 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, andgrepto 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,2and 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
|connectsstdoutof one command tostdinof 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 pipefailto 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
teewithgreporawkfor 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
<<EOFto 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
teeto 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
stderrexplicitly when logging automation. - Prefer
teefor transparency during automation runs. - Use
set -o pipefailfor 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, andelsein 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
ifandcasestatements 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 (
0for 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
findorlsoutput 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 readto process file lines. - 7.5.3 Integration with External Tools
- Combining loops with
cronorsystemdfor scheduled automation. - Incorporating conditional checks and error trapping for robust workflows.
7.6. Hands-On Labsβ
- Build a script that loops through all
/var/wwwdirectories to check disk usage. - Create a
whileloop that pings a server until it responds. - Implement nested loops for multi-site WordPress plugin updates.
- Use
breakandcontinueto 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 -eandtrapfor 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
functionkeyword 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
localprevents 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
localfor 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
returnsends an exit code, not text output.- Use
echoorprintffor text;returnfor 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 -eandtrapto 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 utilitiesbackup.shβ task-specific logicmain.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.shcontaining generic functions likelog_message,check_disk, and reused across all server maintenance scripts.
8.6. Hands-On Labsβ
- Create a modular
backup.shthat 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
localfor safety and readability. - Return codes for automation logic;
echoonly 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, andsedfor structured manipulation. - Example: extract username from
/etc/passwdor 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
[[ ]]:
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
| Operator | Meaning | Example |
-e | File or directory exists | [ -e file.txt ] |
-f | Regular file exists | [ -f script.sh ] |
-d | Directory exists | [ -d /var/www/html ] |
-r | Read permission | [ -r config.php ] |
-w | Write permission | [ -w log.txt ] |
-x | Executable | [ -x deploy.sh ] |
-s | Non-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. Symlinksβ
- 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
realpathto 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
basenameanddirnameto parse file paths dynamically.
10.7. Best Practices & Next Stepsβ
- Always verify existence before modifying or deleting files.
- Avoid using
rm -rfwithout double confirmation or dry-run option. - Use relative paths for portability,
realpathfor 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
| Command | Purpose | Example |
tar -cvf archive.tar file1 file2 | Create archive | tar -cvf backup.tar /var/www/html |
tar -xvf archive.tar | Extract archive | tar -xvf backup.tar -C /restore |
tar -tvf archive.tar | List contents |
- Flags:
cβ createxβ extracttβ listvβ verbosefβ 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/wwwbackup 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
| Command | Description | Example |
gzip file.txt | Compress file | |
gzip -k file.txt | Keep original file | |
gunzip file.txt.gz | Decompress 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
tarand **zip zipcompresses per file;tarbundles before compression.ziparchives are cross-platform friendly (Windows/Linux).- 11.3.2 Syntax
| Command | Description | Example |
zip archive.zip file1 file2 | Create ZIP file | |
unzip archive.zip | Extract files | |
zip -r site.zip /var/www/html | Recursive 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 -tzforgzip -tto 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 β
0for 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:
| Code | Meaning | Example |
| 0 | Success | Command completed normally |
| 1 | General error | Invalid argument |
| 2 | Misuse of shell builtins | Syntax error |
| 127 | Command not found | Typo in command name |
| 130 | Script terminated by Ctrl+C | SIGINT 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 outputstderr(2) β error messages- 12.2.2 Redirection Syntax
| Command | Description |
command 2> error.log | Redirect errors to file |
command &> all.log | Redirect both stdout and stderr |
command 2>> error.log | Append 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
teefor real-time monitoring and logging.
12.3. Traps & Signalsβ
- 12.3.1 What Are Signals
- Signals are OS-level interrupts like
SIGINT(Ctrl+C) orSIGTERM(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
| Signal | Description |
SIGINT | User interrupt (Ctrl+C) |
SIGTERM | Termination signal |
SIGQUIT | Quit signal |
EXIT | Triggered 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
echofor 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 pipefailin 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
nohupto persist after logout:nohup ./script.sh &. - 13.5.4 Integration With System Tools
- Combine with
systemdorcronfor automatic startup. - Monitor using
ps,top, orpgrep. - 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
trapwithkillfor clean shutdowns. - Use
waitto 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
| Command | Description | Example |
date | Show current date/time | Fri Oct 17 14:22:03 UTC 2025 |
date +"%Y-%m-%d" | Custom format (ISO) | 2025-10-17 |
date +"%H:%M:%S" | Time only | 14:22:03 |
date +"%F_%H-%M-%S" | Filename-safe timestamp | 2025-10-17_14-22-03 |
- 14.1.3 Common Format Specifiers
| Symbol | Meaning | Example |
%Y | Year | 2025 |
%m | Month (01β12) | 10 |
%d | Day | 17 |
%H | Hour (00β23) | 14 |
%M | Minute | 22 |
%S | Second | 03 |
%F | Full 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
| Command | Description |
sleep 5 | Pause for 5 seconds |
sleep 2m | Pause for 2 minutes |
sleep 1h | Pause 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
sleepin retry logic:
until ping -c1 server; do
echo "Retrying..."
sleep 5
done
14.4. Script Timingβ
- 14.4.1 The
timeCommand - 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
| Field | Meaning |
real | Total wall-clock time |
user | CPU time in user mode |
sys | CPU 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
| Schedule | Description | Example |
0 2 * * * | Run daily at 2 AM | Database backup |
*/5 * * * * | Every 5 minutes | Health check script |
0 */6 * * * | Every 6 hours | Cache 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
| Command | Description |
at 10pm | Run job at 10 PM today |
at now + 2 hours | Run 2 hours from now |
at 07:30 AM tomorrow | Schedule for next day |
- 15.2.3 Workflow
- Enter commands interactively after
atprompt, pressCtrl+Dto 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
sleepfor 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
logrotateor 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
teeto 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
| Command | Purpose |
systemctl status cron | Check cron service health |
grep CRON /var/log/syslog | View cron activity logs |
atq | List 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
| Symbol | Description | Example |
^ | Start of string | ^root |
$ | End of string | .sh$ |
. | Any single character | h.t |
* | Zero or more occurrences | lo*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
greporawkusing 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
| Type | Example | Notes |
| Backticks | date +%F | Deprecated 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
greporawkto 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
&andwaitfor 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
| Task | Command | Example |
| Add item | array+=(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
&andwait. - 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
waitto 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.