Skip to main content
In shell scripting, robust error handling and input validation are crucial. Earlier, we saw how $? 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

  1. Why $# Matters
  2. Basic Usage of $#
  3. Positional Parameters and Empty Defaults
  4. Guard Clauses with $#
  5. Real-World Example: Walking Calorie Expenditure Script
  6. Summary of Key Variables
  7. 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:
Run it with different argument counts:

Positional Parameters and Empty Defaults

By default, referencing an unset positional parameter expands to an empty string without an error:
Without validation, scripts can continue with missing data, leading to downstream failures.

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

Running without arguments shows a syntax error but exits with status 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


Watch Video