Skip to main content
Command-line arguments are essential in shell scripting for creating flexible, reusable scripts. Instead of hard-coding values, you can accept inputs at runtime—much like using a remote control to switch channels on a TV. This guide covers everything from basic positional parameters to advanced iteration techniques.

Table of Contents


Understanding Positional Parameters

When you invoke a script with arguments:
Inside myscript.sh, the inputs map to:
Output:
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:
This works but requires editing the script for each repository URL.

Parameterizing Your Script

By using $1, you can pass the repository URL when running the script:
Run it as:
Now the script clones any repository you specify.

Common Special Variables

Example:

Handling Maximum Argument Size (ARG_MAX)

Unix-like systems impose a limit on the total size of command-line arguments. Check it with:
On most Linux distributions, 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.

References

Watch Video

Practice Lab