Skip to main content

πŸ“˜ Positional Parameters



🎯 What You Will Learn​

  1. Understand how Bash passes arguments to scripts via positional parameters ($1, $2, $@, etc.).
  2. Learn how to handle, count, and validate input parameters.
  3. Differentiate between $*, $@, $#, $?, $0, and "$@" usage.
  4. Apply positional parameters in WordPress automation (plugin updates, backups, deployments).
  5. Use conditional checks to make scripts dynamic and reusable.
  6. Build input-aware Bash scripts for flexible management workflows.

1. 5W + 1H Framework​

ElementDescription
WhatPositional parameters are automatically assigned variables ($1, $2, $3, etc.) representing arguments passed to a Bash script or function.
WhyThey make scripts reusable and dynamic without hardcoding paths or arguments.
WhoBash users, system admins, and developers automating WordPress server tasks.
WhereInside scripts executed with parameters, such as ./script.sh arg1 arg2.
WhenWhen your Bash script needs external input, like WordPress paths, usernames, or environment modes.
HowUse $1, $2, etc., for specific arguments; $@ or $* for all; $# for count; and shift or loop to handle multiple inputs.

2. Prerequisites​

  • Completed Module 3.2 (Environment Variables).
  • Familiar with executing Bash scripts using parameters (e.g., ./myscript.sh arg1 arg2).
  • Basic understanding of control flow (if, case) and variable declaration.

3. Core Syntax & Concept (Factual & Complete)​

NoSyntax FormulaCommand / TypeSyntax ExampleDescriptionBehavior / Output
1$0Script Nameecho "Script name: $0"Returns the name or path of the current script.Prints script filename.
2$1, $2, ...Positional Parametersecho "First: $1, Second: $2"Represents command-line arguments passed to script.Expands arguments sequentially.
3$#Argument Countecho "Total: $#"Returns number of positional parameters.Displays integer count.
4$@All Arguments (Array-like)echo "$@"Expands to all arguments individually (preserves quoting).Each argument treated separately.
5$*All Arguments (Single String)echo "$*"Expands all arguments as one string (merged).Joins args into one string.
6shift [n]Shift Parametersshift 1Moves argument positions left (drops first).Useful in argument loops.
7"${@:start:end}"Slice Argumentsecho "${@:2:3}"Access subset of positional arguments.Prints selected range.
8$?Exit Codeecho $?Exit status of last executed command.0 = success, non-zero = failure.
9"$@" in loopIterate Argumentsfor arg in "$@"; do echo $arg; doneLoops through each argument separately.Preserves spacing.
10$* in loopIterate Merged Argsfor arg in $*; do echo $arg; doneIterates over all args as one word list.Loses original quoting.
11if [ $# -lt n ]Validate Arg Countif [ $# -lt 2 ]; then echo "Usage: script arg1 arg2"; fiEnsures correct number of parameters.Helps prevent misuse.
12function func() { echo $1; }Positional in Functionfunc helloFunctions also accept $1, $2, etc.Works same as script args.
13$@ with xargsPass Argumentsxargs -n1 echo "$@"Expands script args into another command.Pass-through arguments.
14case $1 in pattern)Conditional Parameter Logiccase $1 in start)Handles specific argument cases.Implements branching logic.

4. Demonstration Example​

Input Script:

#!/bin/bash
echo "Script Name: $0"
echo "First Arg: $1"
echo "Second Arg: $2"
echo "Total Args: $#"
echo "All Args (Quoted): $@"

Run Command:

./demo.sh wpstrategist /home/wpstrategist/public_html

Expected Output:

Script Name: ./demo.sh
First Arg: wpstrategist
Second Arg: /home/wpstrategist/public_html
Total Args: 2
All Args (Quoted): wpstrategist /home/wpstrategist/public_html

Explanation: Each argument maps sequentially to $1, $2, etc. $@ expands all arguments while $# counts them.​

5. Use Cases (WordPress-VPS Focused)​

5.1 (Ref: #2) Passing Domain and Path​

Input:

#!/bin/bash
domain=$1
wp_path=$2
echo "Running updates for $domain..."
wp plugin update --all --path="$wp_path" --allow-root

Command:

./wp_update.sh metaxenith.com /home/metaxenith/public_html

Expected Output:

Running updates for metaxenith.com...
Success: Updated all plugins.

Explanation: Takes domain and path as dynamic input for multi-site automation.​

5.2 (Ref: #3) Counting Input Parameters​

#!/bin/bash
if [ $# -lt 2 ]; then
echo "Usage: $0 domain path"
exit 1
fi
echo "Arguments verified: $# provided"

Run Command:

./verify.sh wpstrategist /home/wpstrategist/public_html

Expected Output:

Arguments verified: 2 provided

Use Case: Ensures required input arguments are supplied before running critical actions.​

5.3 (Ref: #9) Iterating Over WordPress Sites​

#!/bin/bash
for site in "$@"; do
echo "Updating: $site"
wp plugin update --all --path="/home/$site/public_html" --allow-root
done

Run Command:

./batch_update.sh wpstrategist metaxenith id86net

Expected Output:

Updating: wpstrategist
Updating: metaxenith
Updating: id86net

Explanation: Loops through each argument for bulk updates across multiple WP installs.​

5.4 (Ref: #6) Using Shift to Process Arguments Sequentially​

#!/bin/bash
while [ $# -gt 0 ]; do
echo "Processing $1..."
shift
done

Run Command:

./process.sh dev_wp metaxenith id86net

Expected Output:

Processing dev_wp...
Processing metaxenith...
Processing id86net...

Use Case: Sequential argument processing in iterative scripts.​

5.5 (Ref: #11) Argument Validation for Backup Script​

#!/bin/bash
if [ $# -ne 2 ]; then
echo "Usage: $0 <domain> <path>"
exit 1
fi

domain=$1
path=$2
tar -czf "/home/wpbackup/${domain}_$(date +%F).tar.gz" "$path"
echo "Backup created for $domain."

Run Command:

./wp_backup.sh metaxenith /home/metaxenith/public_html

Expected Output:

Backup created for metaxenith.

Explanation: Ensures exactly two arguments are passed (domain & directory).​

5.6 (Ref: #12) Using Positional Parameters in a Function​

function wpinfo() {
echo "Site: $1"
echo "Path: $2"
}
wpinfo wpstrategist /var/www/html

Expected Output:

Site: wpstrategist
Path: /var/www/html

Use Case: Functions accept positional parameters just like scripts β€” modular automation.​

5.7 (Ref: #14) Conditional Execution Using Case​

#!/bin/bash
case $1 in
start)
echo "Starting OpenLiteSpeed..."
systemctl start lsws
;;
stop)
echo "Stopping OpenLiteSpeed..."
systemctl stop lsws
;;
restart)
echo "Restarting OpenLiteSpeed..."
systemctl restart lsws
;;
*)
echo "Usage: $0 {start|stop|restart}"
;;
esac

Run Command:

./ols_control.sh restart

Expected Output:

Restarting OpenLiteSpeed...

Explanation: Positional parameters enable command-driven server control.​

6. Best Practices​

PracticeDescription
Always validate argument count ($#)Prevents misuse and missing parameters.
Use quotes around $@Preserves arguments with spaces.
Prefer $@ over $*$@ retains argument boundaries.
Include usage message ($0)Guides user when arguments are missing.
Use shift for argument loopsCleanly processes multi-input scripts.
Keep argument order consistentReduces confusion in automation chains.

7. Common Mistakes & Fixes​

MistakeWrong ExampleCorrect ExampleExplanation
Forgetting to quote $@for arg in $@for arg in "$@"Unquoted loses argument separation.
Miscounting parametersif [ $# < 2 ]if [ $# -lt 2 ]Wrong operator syntax.
Forgetting $ before variableecho 1echo $1$ required to reference.
Using $* instead of $@"$*" merges arguments"$@" keeps them distinctUse correct expansion type.
Skipping validationDirectly using $1Check if [ -z "$1" ]Avoid null parameter usage.

8. Quick Lab – WordPress Plugin Automation Script​

Script: wp_batch_update.sh

#!/bin/bash
# --------------------------------------------
# Script Name : wp_batch_update.sh
# Purpose : Update multiple WP sites using positional parameters
# Usage : ./wp_batch_update.sh site1 site2 site3
# --------------------------------------------

if [ $# -lt 1 ]; then
echo "Usage: $0 <site1> <site2> ..."
exit 1
fi

for site in "$@"; do
echo "πŸ”§ Updating $site ..."
wp plugin update --all --path="/home/$site/public_html" --allow-root
done

echo "βœ… All updates complete."

Run Command:

./wp_batch_update.sh wpstrategist metaxenith id86net

Expected Output:

πŸ”§ Updating wpstrategist ...
πŸ”§ Updating metaxenith ...
πŸ”§ Updating id86net ...
βœ… All updates complete.

Explanation: Script accepts unlimited site names as arguments and automates bulk plugin updates efficiently.​

9. Troubleshooting Matrix​

IssueSymptomCauseSolution
Script fails due to missing argsβ€œNo such file or directory”$1 not passedAdd usage validation.
Arguments with spaces breakMulti-word site pathNot quoted properlyUse "$@" or quote $path.
Loop skips parametersUsing $* unquotedLoses argument boundariesAlways use "$@".
Command executes wrong siteArgument order mismatched$1, $2 swappedMaintain consistent usage order.

10. Static vs Dynamic Framing​

FramingDescriptionBehavior
StaticScript uses fixed paths or domainsLimited flexibility but predictable.
DynamicScript uses $1, $2, $@ inputsAdaptable, reusable, and automation-ready.

11. Cheat Sheet​

TaskSyntax / Example
Access script name$0
First argument$1
All arguments"$@"
Count arguments$#
Shift argumentsshift
Validate minimum argsif [ $# -lt n ]
Iterate allfor arg in "$@"; do ...; done
Slice args"${@:2:3}"
Case handling`case $1 in start
Check argument presence[ -z "$1" ] && echo "Missing input"

12. Mini-Quiz​

#QuestionAnswer
1What does $1 represent?The first argument passed to the script.
2What’s the difference between $@ and $*?$@ preserves separation; $* merges into one string.
3How do you count the number of arguments?Use $#.
4How do you remove the first argument in a loop?Use shift.
5How do you ensure the user passes at least one argument?Use if [ $# -lt 1 ]; then ... fi.

Would you like me to continue next with πŸ“˜ Module 3.4 – Special Variables ($?, $$, $!, $UID, $RANDOM) using the same instructional depth and formatting style?