Managing WordPress installations manually through the administrative web interface is acceptable for a single personal blog, but it quickly becomes an inefficient, repetitive nightmare for sysadmins, agencies, and hosting providers responsible for dozens of production sites. Clicking through update prompts, manually exporting database dumps via phpMyAdmin, and troubleshooting plugin conflicts inside a browser consumes valuable engineering hours.
WP-CLI—the official command-line interface for WordPress—allows you to perform virtually any administrative action from the Linux terminal without touching a web browser. By combining WP-CLI with modular Bash scripts on your Linux VPS, you can automate routine security updates, transient cleanups, permission enforcement, and automated database backups with surgical precision. Below are 10 production-tested Bash scripts every WordPress engineer should deploy.
1. Automated Non-Breaking Plugin & Core Updates
Safely update minor security patches for WordPress core and active plugins while bypassing major releases that could introduce compatibility issues:
#!/usr/bin/env bash
WP_PATH="/var/www/my-site"
echo "Checking for minor security updates in ${WP_PATH}..."
# Update core minor releases only (e.g., 6.5.1 to 6.5.2)
wp core update --minor --path="${WP_PATH}" --allow-root
# Update plugins and clear object cache
wp plugin update --all --path="${WP_PATH}" --allow-root
wp cache flush --path="${WP_PATH}" --allow-root
echo "Updates applied successfully!"
2. Atomic Automated Database Backup with Gzip Compression
Dumping your database using WP-CLI guarantees proper table locking and exports cleanly without web server execution timeouts:
#!/usr/bin/env bash
WP_PATH="/var/www/my-site"
BACKUP_DIR="/opt/backups/db"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
mkdir -p "${BACKUP_DIR}"
# Export database directly through gzip stream
wp db export - --path="${WP_PATH}" --allow-root | gzip -9 > "${BACKUP_DIR}/wp_db_${TIMESTAMP}.sql.gz"
# Retain only last 14 days of dumps
find "${BACKUP_DIR}" -type f -name "*.sql.gz" -mtime +14 -delete
echo "Database backed up to ${BACKUP_DIR}/wp_db_${TIMESTAMP}.sql.gz"
3. Transient & Expired Option Garbage Collection
Over time, WordPress plugins litter the wp_options table with expired transients that slow down autoloaded option queries. Clean them up instantly:
#!/usr/bin/env bash
WP_PATH="/var/www/my-site"
echo "Purging expired transients from ${WP_PATH}..."
wp transient delete --expired --path="${WP_PATH}" --allow-root
# Optimize database overhead after delete
wp db optimize --path="${WP_PATH}" --allow-root
4. Production File & Directory Permissions Auditor
Ensure web server permissions conform strictly to Linux security baselines (755 directories, 644 files, 400 wp-config.php):
#!/usr/bin/env bash
WP_PATH="/var/www/my-site"
WEB_USER="www-data"
echo "Enforcing hardened file permissions on ${WP_PATH}..."
chown -R ${WEB_USER}:${WEB_USER} "${WP_PATH}"
find "${WP_PATH}" -type d -exec chmod 755 {} \;
find "${WP_PATH}" -type f -exec chmod 644 {} \;
chmod 400 "${WP_PATH}/wp-config.php"
echo "Security permissions locked down."
5. Automated Malware & Core File Integrity Check
Compare every file in your core WordPress installation against the official WordPress.org cryptographic checksums:
#!/usr/bin/env bash
WP_PATH="/var/www/my-site"
echo "Verifying WordPress core file checksums..."
if ! wp core verify-checksums --path="${WP_PATH}" --allow-root; then
echo "WARNING: Core files modified or corrupted! Reinstalling core..."
wp core download --skip-content --force --path="${WP_PATH}" --allow-root
else
echo "Core integrity confirmed 100% clean."
fi
6. Global Search and Replace for Domain Migration
Serializing PHP strings safely during domain migrations prevents broken widgets, menus, and theme options:
#!/usr/bin/env bash
WP_PATH="/var/www/my-site"
OLD_URL="https://dev.example.com"
NEW_URL="https://example.com"
echo "Executing serialized search and replace..."
wp search-replace "${OLD_URL}" "${NEW_URL}" --all-tables --precise --recurse-objects --path="${WP_PATH}" --allow-root
wp cache flush --path="${WP_PATH}" --allow-root
7. Staging Site Clone & Sanitization
Quickly clone a production database into staging while scrambling customer email addresses to prevent accidental marketing blasts:
#!/usr/bin/env bash
PROD_PATH="/var/www/production"
STAGE_PATH="/var/www/staging"
echo "Syncing production database to staging..."
wp db export /tmp/prod_dump.sql --path="${PROD_PATH}" --allow-root
wp db import /tmp/prod_dump.sql --path="${STAGE_PATH}" --allow-root
rm -f /tmp/prod_dump.sql
# Scramble user emails in staging
wp db query "UPDATE wp_users SET user_email = CONCAT('user_', ID, '@staging.local') WHERE ID > 1;" --path="${STAGE_PATH}" --allow-root
echo "Staging environment refreshed and sanitized."
8. WooCommerce Orphaned Order Metadata Purge
Reclaim gigabytes of database space by deleting orphaned postmeta rows that remain after order deletions:
#!/usr/bin/env bash
WP_PATH="/var/www/my-site"
echo "Cleaning orphaned postmeta..."
wp db query "DELETE pm FROM wp_postmeta pm LEFT JOIN wp_posts wp ON wp.ID = pm.post_id WHERE wp.ID IS NULL;" --path="${WP_PATH}" --allow-root
echo "Orphaned metadata purged."
9. Emergency Administrative Password Reset
Instantly reset administrative credentials when locked out by MFA or credential loss:
#!/usr/bin/env bash
WP_PATH="/var/www/my-site"
ADMIN_USER="siteadmin"
NEW_PASS=$(openssl rand -base64 16)
wp user update "${ADMIN_USER}" --user_pass="${NEW_PASS}" --path="${WP_PATH}" --allow-root
echo "Temporary Password generated for ${ADMIN_USER}: ${NEW_PASS}"
10. Cron Daemon Scheduled Tasks Health Monitor
Inspect blocked or deadlocked wp-cron scheduled events directly from the terminal:
#!/usr/bin/env bash
WP_PATH="/var/www/my-site"
echo "Inspecting active WP-Cron scheduled hooks..."
wp cron event list --fields=hook,next_run_relative,status --path="${WP_PATH}" --allow-root
# Force run stuck crons
wp cron event run --due-now --path="${WP_PATH}" --allow-root
Advanced WP-CLI Automation: Multi-Site Loops & Cron Integration
Elevate your WP-CLI automation from single-site utilities into fleet-wide management engines capable of managing hundreds of production WordPress installations:
- Automating Multi-Site Maintenance Loops: Execute updates, security scans, and database optimizations across every site on a server using an automated directory loop:
#!/usr/bin/env bash # Iterate through all web roots in /var/www for SITE_DIR in /var/www/*/public_html; do if [ -f "${SITE_DIR}/wp-config.php" ]; then echo "Processing site: ${SITE_DIR}..." wp plugin update --all --path="${SITE_DIR}" --allow-root --quiet wp core update --minor --path="${SITE_DIR}" --allow-root --quiet wp transient delete --expired --path="${SITE_DIR}" --allow-root --quiet wp cache flush --path="${SITE_DIR}" --allow-root --quiet fi done echo "Fleet-wide maintenance routine completed successfully!" - Replacing Web-Triggered WP-Cron with System Cron: By default, WordPress executes scheduled tasks (publishing scheduled posts, processing WooCommerce subscription renewals) whenever a public visitor hits a page. On low-traffic sites, crons run late; on high-traffic sites, duplicate cron calls choke the server. Disable web cron in
wp-config.phpand execute WP-CLI via system crontab every 5 minutes:# In wp-config.php define('DISABLE_WP_CRON', true); # In /etc/crontab */5 * * * * www-data /usr/local/bin/wp cron event run --due-now --path=/var/www/my-site --quiet - Monitoring WP-CLI Exit Codes in Monitoring Systems: When incorporating WP-CLI scripts into Datadog, Zabbix, or Uptime Kuma, ensure commands return standard POSIX exit status codes (
0for success, non-zero for failure) to trigger automated sysadmin alerts.
Automate High-Performance WordPress on CpanelFree VPS
Run automated WP-CLI pipelines, scheduled backups, and custom bash scripts with complete root access, unmetered bandwidth, and lightning-fast NVMe storage on CpanelFree.
