$? 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:
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.