π Positional Parameters
π― What You Will Learnβ
- Understand how Bash passes arguments to scripts via positional parameters (
$1,$2,$@, etc.). - Learn how to handle, count, and validate input parameters.
- Differentiate between
$*,$@,$#,$?,$0, and"$@"usage. - Apply positional parameters in WordPress automation (plugin updates, backups, deployments).
- Use conditional checks to make scripts dynamic and reusable.
- Build input-aware Bash scripts for flexible management workflows.
1. 5W + 1H Frameworkβ
| Element | Description |
| What | Positional parameters are automatically assigned variables ($1, $2, $3, etc.) representing arguments passed to a Bash script or function. |
| Why | They make scripts reusable and dynamic without hardcoding paths or arguments. |
| Who | Bash users, system admins, and developers automating WordPress server tasks. |
| Where | Inside scripts executed with parameters, such as ./script.sh arg1 arg2. |
| When | When your Bash script needs external input, like WordPress paths, usernames, or environment modes. |
| How | Use $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)β
| No | Syntax Formula | Command / Type | Syntax Example | Description | Behavior / Output |
| 1 | $0 | Script Name | echo "Script name: $0" | Returns the name or path of the current script. | Prints script filename. |
| 2 | $1, $2, ... | Positional Parameters | echo "First: $1, Second: $2" | Represents command-line arguments passed to script. | Expands arguments sequentially. |
| 3 | $# | Argument Count | echo "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. |
| 6 | shift [n] | Shift Parameters | shift 1 | Moves argument positions left (drops first). | Useful in argument loops. |
| 7 | "${@:start:end}" | Slice Arguments | echo "${@:2:3}" | Access subset of positional arguments. | Prints selected range. |
| 8 | $? | Exit Code | echo $? | Exit status of last executed command. | 0 = success, non-zero = failure. |
| 9 | "$@" in loop | Iterate Arguments | for arg in "$@"; do echo $arg; done | Loops through each argument separately. | Preserves spacing. |
| 10 | $* in loop | Iterate Merged Args | for arg in $*; do echo $arg; done | Iterates over all args as one word list. | Loses original quoting. |
| 11 | if [ $# -lt n ] | Validate Arg Count | if [ $# -lt 2 ]; then echo "Usage: script arg1 arg2"; fi | Ensures correct number of parameters. | Helps prevent misuse. |
| 12 | function func() { echo $1; } | Positional in Function | func hello | Functions also accept $1, $2, etc. | Works same as script args. |
| 13 | $@ with xargs | Pass Arguments | xargs -n1 echo "$@" | Expands script args into another command. | Pass-through arguments. |
| 14 | case $1 in pattern) | Conditional Parameter Logic | case $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β
| Practice | Description |
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 loops | Cleanly processes multi-input scripts. |
| Keep argument order consistent | Reduces confusion in automation chains. |
7. Common Mistakes & Fixesβ
| Mistake | Wrong Example | Correct Example | Explanation |
Forgetting to quote $@ | for arg in $@ | for arg in "$@" | Unquoted loses argument separation. |
| Miscounting parameters | if [ $# < 2 ] | if [ $# -lt 2 ] | Wrong operator syntax. |
Forgetting $ before variable | echo 1 | echo $1 | $ required to reference. |
Using $* instead of $@ | "$*" merges arguments | "$@" keeps them distinct | Use correct expansion type. |
| Skipping validation | Directly using $1 | Check 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β
| Issue | Symptom | Cause | Solution |
| Script fails due to missing args | βNo such file or directoryβ | $1 not passed | Add usage validation. |
| Arguments with spaces break | Multi-word site path | Not quoted properly | Use "$@" or quote $path. |
| Loop skips parameters | Using $* unquoted | Loses argument boundaries | Always use "$@". |
| Command executes wrong site | Argument order mismatched | $1, $2 swapped | Maintain consistent usage order. |
10. Static vs Dynamic Framingβ
| Framing | Description | Behavior |
| Static | Script uses fixed paths or domains | Limited flexibility but predictable. |
| Dynamic | Script uses $1, $2, $@ inputs | Adaptable, reusable, and automation-ready. |
11. Cheat Sheetβ
| Task | Syntax / Example |
| Access script name | $0 |
| First argument | $1 |
| All arguments | "$@" |
| Count arguments | $# |
| Shift arguments | shift |
| Validate minimum args | if [ $# -lt n ] |
| Iterate all | for 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β
| # | Question | Answer |
| 1 | What does $1 represent? | The first argument passed to the script. |
| 2 | Whatβs the difference between $@ and $*? | $@ preserves separation; $* merges into one string. |
| 3 | How do you count the number of arguments? | Use $#. |
| 4 | How do you remove the first argument in a loop? | Use shift. |
| 5 | How 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?