<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>bash argument parsing Archives - WP-CLI Mastery</title>
	<atom:link href="https://wpclimastery.com/blog/tag/bash-argument-parsing/feed/" rel="self" type="application/rss+xml" />
	<link>https://wpclimastery.com/blog/tag/bash-argument-parsing/</link>
	<description>Automate WordPress Like a DevOps Pro.</description>
	<lastBuildDate>Mon, 24 Nov 2025 11:16:24 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://wpclimastery.com/wp-content/uploads/2025/11/cropped-favicon-32x32.webp</url>
	<title>bash argument parsing Archives - WP-CLI Mastery</title>
	<link>https://wpclimastery.com/blog/tag/bash-argument-parsing/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Parse Command Line Arguments in WP-CLI Bash Scripts</title>
		<link>https://wpclimastery.com/blog/how-to-parse-command-line-arguments-in-wp-cli-bash-scripts/</link>
					<comments>https://wpclimastery.com/blog/how-to-parse-command-line-arguments-in-wp-cli-bash-scripts/#respond</comments>
		
		<dc:creator><![CDATA[Krasen]]></dc:creator>
		<pubDate>Mon, 24 Nov 2025 11:16:24 +0000</pubDate>
				<category><![CDATA[Bash Scripting for WordPress]]></category>
		<category><![CDATA[bash argument parsing]]></category>
		<category><![CDATA[bash getopts]]></category>
		<category><![CDATA[bash parameters]]></category>
		<category><![CDATA[command line arguments]]></category>
		<category><![CDATA[wp-cli scripting]]></category>
		<guid isPermaLink="false">https://wpclimastery.com/?p=228</guid>

					<description><![CDATA[<p>When building automation scripts for WordPress using WP-CLI, the ability to parse command line arguments effectively transforms rigid scripts into flexible, reusable tools. Whether you&#8217;re managing multiple sites or creating...</p>
<p>The post <a href="https://wpclimastery.com/blog/how-to-parse-command-line-arguments-in-wp-cli-bash-scripts/">How to Parse Command Line Arguments in WP-CLI Bash Scripts</a> appeared first on <a href="https://wpclimastery.com">WP-CLI Mastery</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>When building automation scripts for WordPress using WP-CLI, the ability to parse command line arguments effectively transforms rigid scripts into flexible, reusable tools. Whether you&#8217;re managing multiple sites or creating custom deployment workflows, understanding argument parsing is essential for professional WordPress development.</p>



<h2 class="wp-block-heading" id="why-parse-arguments-in-wp-cli-scripts">Why Parse Arguments in WP-CLI Scripts?</h2>



<p>Command line argument parsing enables your Bash scripts to accept dynamic input, making them adaptable to different scenarios without code modifications. Instead of hardcoding site URLs, environment types, or backup paths, you can pass these values as arguments when executing your scripts.</p>



<p>This approach brings several advantages: increased script reusability, reduced maintenance overhead, better error handling, and improved user experience. A well-designed script with proper argument parsing can serve multiple purposes across different WordPress installations.</p>



<h2 class="wp-block-heading" id="understanding-positional-parameters">Understanding Positional Parameters</h2>



<p>The simplest form of argument parsing uses positional parameters. In Bash, arguments passed to a script are automatically assigned to special variables:&nbsp;<code>$1</code>&nbsp;for the first argument,&nbsp;<code>$2</code>&nbsp;for the second, and so on. The&nbsp;<code>$0</code>&nbsp;variable contains the script name itself.</p>



<pre class="wp-block-code"><code>#!/bin/bash
<em># Simple WP-CLI backup script with positional parameters</em>

SITE_PATH=$1
BACKUP_DIR=$2

wp --path="$SITE_PATH" db export "$BACKUP_DIR/database-$(date +%Y%m%d).sql"
</code></pre>



<p>Execute this script with:&nbsp;<code>./backup.sh /var/www/html /backups</code></p>



<p>While positional parameters work for simple cases, they have limitations. Users must remember the exact order of arguments, and the script offers no built-in way to handle optional parameters or provide helpful usage information.</p>



<h2 class="wp-block-heading" id="using-getopts-for-named-options">Using getopts for Named Options</h2>



<p>The&nbsp;<code>getopts</code>&nbsp;command provides a more sophisticated approach to argument parsing, allowing you to define named options with single-character flags. This method significantly improves script usability and maintainability.</p>



<pre class="wp-block-code"><code>#!/bin/bash
<em># WP-CLI deployment script with getopts</em>

usage() {
    echo "Usage: $0 -p &lt;path&gt; -e &lt;environment&gt; &#91;-b]"
    echo "  -p    WordPress installation path"
    echo "  -e    Environment (dev|staging|prod)"
    echo "  -b    Create backup before deployment"
    exit 1
}

BACKUP=false

while getopts "p:e:bh" opt; do
    case $opt in
        p) WP_PATH="$OPTARG" ;;
        e) ENVIRONMENT="$OPTARG" ;;
        b) BACKUP=true ;;
        h) usage ;;
        \?) echo "Invalid option: -$OPTARG" &gt;&amp;2; usage ;;
        :) echo "Option -$OPTARG requires an argument" &gt;&amp;2; usage ;;
    esac
done

<em># Validate required arguments</em>
if &#91;&#91; -z "$WP_PATH" ]] || &#91;&#91; -z "$ENVIRONMENT" ]]; then
    echo "Error: Missing required arguments"
    usage
fi

<em># Script logic continues here</em>
if &#91;&#91; "$BACKUP" == true ]]; then
    wp --path="$WP_PATH" db export "backup-pre-deploy-$(date +%Y%m%d-%H%M%S).sql"
fi
</code></pre>



<p>In this example, options followed by a colon (like&nbsp;<code>p:</code>&nbsp;and&nbsp;<code>e:</code>) require arguments, while standalone letters (like&nbsp;<code>b</code>) act as flags. The&nbsp;<code>OPTARG</code>&nbsp;variable holds the value passed to options requiring arguments.</p>



<h2 class="wp-block-heading" id="advanced-argument-validation">Advanced Argument Validation</h2>



<p>Robust scripts validate input before processing. Argument validation prevents errors, protects against malicious input, and provides clear feedback when users make mistakes.</p>



<pre class="wp-block-code"><code>#!/bin/bash
<em># WP-CLI site migration script with validation</em>

validate_path() {
    if &#91;&#91; ! -d "$1" ]]; then
        echo "Error: Path '$1' does not exist"
        exit 1
    fi

    if &#91;&#91; ! -f "$1/wp-config.php" ]]; then
        echo "Error: '$1' is not a WordPress installation"
        exit 1
    fi
}

validate_environment() {
    local env=$1
    case $env in
        dev|development|staging|production|prod)
            return 0
            ;;
        *)
            echo "Error: Invalid environment '$env'"
            echo "Allowed values: dev, staging, production"
            exit 1
            ;;
    esac
}

<em># After parsing arguments with getopts</em>
validate_path "$WP_PATH"
validate_environment "$ENVIRONMENT"
</code></pre>



<h2 class="wp-block-heading" id="handling-long-form-options">Handling Long-Form Options</h2>



<p>While getopts handles short options well, it doesn&#8217;t natively support long-form options like&nbsp;<code>--path</code>&nbsp;or&nbsp;<code>--environment</code>. For scripts requiring both short and long options, you can implement manual parsing:</p>



<pre class="wp-block-code"><code>#!/bin/bash

while &#91;&#91; $# -gt 0 ]]; do
    case $1 in
        -p|--path)
            WP_PATH="$2"
            shift 2
            ;;
        -e|--environment)
            ENVIRONMENT="$2"
            shift 2
            ;;
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        -h|--help)
            usage
            ;;
        *)
            echo "Unknown option: $1"
            usage
            ;;
    esac
done
</code></pre>



<p>The&nbsp;<code>shift</code>&nbsp;command removes processed arguments from the parameter list, allowing the loop to progress through all provided options.</p>



<h2 class="wp-block-heading" id="practical-example-multi-site-update-script">Practical Example: Multi-Site Update Script</h2>



<p>Here&#8217;s a complete example demonstrating argument parsing in a real-world WP-CLI script:</p>



<pre class="wp-block-code"><code>#!/bin/bash
<em># Update multiple WordPress sites with flexible options</em>

set -euo pipefail

usage() {
    cat &lt;&lt; EOF
Usage: $0 -s &lt;sites&gt; &#91;OPTIONS]

Required:
    -s, --sites       Comma-separated list of site paths

Options:
    -c, --core        Update WordPress core
    -p, --plugins     Update plugins
    -t, --themes      Update themes
    -a, --all         Update everything
    --exclude-plugin  Plugin to exclude (can be used multiple times)
    --dry-run         Show what would be updated without making changes
    -h, --help        Display this help message

Example:
    $0 -s "/var/www/site1,/var/www/site2" --all --exclude-plugin akismet
EOF
    exit 1
}

<em># Initialize variables</em>
SITES=""
UPDATE_CORE=false
UPDATE_PLUGINS=false
UPDATE_THEMES=false
DRY_RUN=false
EXCLUDED_PLUGINS=()

<em># Parse arguments</em>
while &#91;&#91; $# -gt 0 ]]; do
    case $1 in
        -s|--sites) SITES="$2"; shift 2 ;;
        -c|--core) UPDATE_CORE=true; shift ;;
        -p|--plugins) UPDATE_PLUGINS=true; shift ;;
        -t|--themes) UPDATE_THEMES=true; shift ;;
        -a|--all) UPDATE_CORE=true; UPDATE_PLUGINS=true; UPDATE_THEMES=true; shift ;;
        --exclude-plugin) EXCLUDED_PLUGINS+=("$2"); shift 2 ;;
        --dry-run) DRY_RUN=true; shift ;;
        -h|--help) usage ;;
        *) echo "Unknown option: $1"; usage ;;
    esac
done

<em># Validate required arguments</em>
if &#91;&#91; -z "$SITES" ]]; then
    echo "Error: Sites parameter is required"
    usage
fi

<em># Convert comma-separated sites to array</em>
IFS=',' read -ra SITE_ARRAY &lt;&lt;&lt; "$SITES"

<em># Process each site</em>
for site in "${SITE_ARRAY&#91;@]}"; do
    echo "Processing: $site"

    if &#91;&#91; "$UPDATE_CORE" == true ]]; then
        if &#91;&#91; "$DRY_RUN" == true ]]; then
            wp --path="$site" core check-update
        else
            wp --path="$site" core update
        fi
    fi

    if &#91;&#91; "$UPDATE_PLUGINS" == true ]]; then
        EXCLUDE_ARGS=""
        for plugin in "${EXCLUDED_PLUGINS&#91;@]}"; do
            EXCLUDE_ARGS+=" --exclude=$plugin"
        done

        if &#91;&#91; "$DRY_RUN" == true ]]; then
            wp --path="$site" plugin list --update=available
        else
            wp --path="$site" plugin update --all $EXCLUDE_ARGS
        fi
    fi

    if &#91;&#91; "$UPDATE_THEMES" == true ]]; then
        if &#91;&#91; "$DRY_RUN" == true ]]; then
            wp --path="$site" theme list --update=available
        else
            wp --path="$site" theme update --all
        fi
    fi
done

echo "Update process completed successfully"
</code></pre>



<p>This script demonstrates several best practices: comprehensive usage documentation, boolean flags for optional features, array handling for multiple values, validation of required parameters, and safe execution with&nbsp;<code>set -euo pipefail</code>.</p>



<h2 class="wp-block-heading" id="best-practices-for-argument-parsing">Best Practices for Argument Parsing</h2>



<p>Always provide clear usage documentation that users can access with&nbsp;<code>-h</code>&nbsp;or&nbsp;<code>--help</code>. Validate all input before processing to catch errors early. Use meaningful variable names that clarify the purpose of each argument.</p>



<p>Set default values for optional parameters to ensure predictable behavior. Implement proper error handling with informative messages. Consider the order of operations when multiple flags interact.</p>



<p>For production scripts, add the&nbsp;<code>set -euo pipefail</code>&nbsp;directive at the beginning. This makes your script exit on errors, prevents using undefined variables, and ensures pipeline failures are caught.</p>



<h2 class="wp-block-heading" id="testing-your-argument-parsing">Testing Your Argument Parsing</h2>



<p>Test your scripts with various input combinations: missing required arguments, invalid values, conflicting options, and edge cases. Create a test suite that validates expected behavior:</p>



<pre class="wp-block-code"><code><em># Test missing required argument</em>
./script.sh  <em># Should show usage</em>

<em># Test invalid environment</em>
./script.sh -p /var/www/html -e invalid  <em># Should error</em>

<em># Test dry run mode</em>
./script.sh -s "/var/www/site1" --all --dry-run  <em># Should only show what would change</em>
</code></pre>



<h2 class="wp-block-heading" id="related-links">Related Links</h2>



<ul class="wp-block-list">
<li><a href="https://wp-cli.org/">WP-CLI Official Documentation</a></li>



<li><a href="https://tldp.org/LDP/abs/html/">Bash Scripting Guide &#8211; Advanced Topics</a></li>



<li><a href="https://developer.wordpress.org/cli/commands/">WP-CLI Commands Reference</a></li>



<li><a href="https://developer.wordpress.org/apis/">WordPress Automation Best Practices</a></li>



<li><a href="https://www.shellcheck.net/">Shell Script Security Considerations</a></li>
</ul>
<p>The post <a href="https://wpclimastery.com/blog/how-to-parse-command-line-arguments-in-wp-cli-bash-scripts/">How to Parse Command Line Arguments in WP-CLI Bash Scripts</a> appeared first on <a href="https://wpclimastery.com">WP-CLI Mastery</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://wpclimastery.com/blog/how-to-parse-command-line-arguments-in-wp-cli-bash-scripts/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
