$? captures the exit status of the last command. In this guide, we’ll dive into $#, which returns the number of positional parameters passed to your script or function. By checking $# early, you can prevent unexpected behavior and make your scripts more reliable.
Table of Contents
- Why
$#Matters - Basic Usage of
$# - Positional Parameters and Empty Defaults
- Guard Clauses with
$# - Real-World Example: Walking Calorie Expenditure Script
- Summary of Key Variables
- Links and References
Why $# Matters
Shell scripts often rely on user-supplied arguments. If your script assumes a certain number of inputs but none (or too many) are provided, it can silently fail or produce erroneous results. Checking $# allows you to:
- Validate inputs before executing critical logic
- Provide clear usage messages
- Exit early on misuse
Always validate positional parameters to avoid silent errors and improve script maintainability.
Basic Usage of $#
Create a script called count-args.sh:
Positional Parameters and Empty Defaults
By default, referencing an unset positional parameter expands to an empty string without an error:Guard Clauses with $#
Validate $# early in your script to enforce expected usage. Below are common patterns:
| Pattern | Description | Example | ||||
|---|---|---|---|---|---|---|
[[ $# -ne N ]] | Exact number of arguments | if [[ $# -ne 1 ]]; then echo "Usage: $0 <arg>" >&2; exit 1; fi | ||||
[[ $# -lt N ]] | At least N arguments | if [[ $# -lt 1 ]]; then echo "Need at least one arg" >&2; exit 1; fi | ||||
| `[[ $# -lt MIN | $# -gt MAX ]]` | Between MIN and MAX args | `if [[ $# -lt 1 | $# -gt 2 ]]; then echo “Expect 1–2 args” >&2; exit 1; fi` |
Exact Number of Arguments
Minimum Number of Arguments
Range of Arguments
Real-World Example: Walking Calorie Expenditure Script
Calculating calories burned from step counts is a practical script. Let’s see a flawed version and then improve it with input validation.Flawed Version
0:
Scripts that continue after errors can hide critical failures. Always combine guard clauses with strict error handling.
Improved Version with set -e and terminate()
Usage
Summary of Key Variables
| Variable | Description | Example |
|---|---|---|
$? | Exit status of the last command | echo $? |
$# | Number of positional parameters passed to a script | if [[ $# -ne 1 ]]; then ... fi |
$1, $2 | Positional parameters (first, second, etc.) | echo "First: $1" |