Table of Contents
- Understanding Positional Parameters
- Practical Example: Cloning and Counting Files
- Parameterizing Your Script
- Common Special Variables
- Handling Maximum Argument Size (
ARG_MAX) - Iterating with
shift - References
Understanding Positional Parameters
When you invoke a script with arguments:myscript.sh, the inputs map to:
Always quote your positional parameters to handle spaces and special characters safely:
Practical Example: Cloning and Counting Files
Suppose you need to clone a Git repository and count its files. A hard-coded approach looks like this:Parameterizing Your Script
By using$1, you can pass the repository URL when running the script:
Common Special Variables
| Variable | Description | Example Output |
|---|---|---|
$0 | Script name | ./myscript.sh |
$1, $2, … | First, second, … arguments | apple banana |
$# | Total number of arguments | 3 |
$@ | All arguments as separate words | apple banana cherry |
$* | All arguments as a single word ("$*" joins) | apple banana cherry |
Handling Maximum Argument Size (ARG_MAX)
Unix-like systems impose a limit on the total size of command-line arguments. Check it with:
ARG_MAX is around 1 MiB, which is sufficient for tens of thousands of small arguments.
Exceeding
ARG_MAX will cause a “Argument list too long” error. For bulk operations, consider using xargs or reading from a file.Iterating with shift
The shift command discards $1 and shifts all other parameters down by one. This is useful when you don’t know the number of arguments in advance:
Command-line arguments empower you to build dynamic, user-driven shell scripts. Next up: advanced option parsing with
getopts and long-form flags.