Command Line Arguments in Shell Scripts
Command line arguments allow users to pass input directly to a script when executing it. This makes scripts dynamic and flexible, enabling them to handle varying input without modifying the code.
Accessing Command Line Arguments
In Bash, arguments passed to a script can be accessed using special variables:
Variable | Description |
---|---|
$0 | Name of the script |
$1, $2, ... | Positional arguments (first, second, etc.) |
$# | Total number of arguments passed |
$@ | All arguments as a single string |
$* | All arguments as a single string (slightly different from $@ ) |
$? | Exit status of the last executed command |
$$ | Process ID (PID) of the current script |
Example: Simple Argument Handling
Execution:
Output:
Using All Arguments ($@
vs $*
)
Example:
Execution:
Output:
Key Difference:
$@
: Treats each argument as a separate string.$*
: Treats all arguments as a single string.
Looping Through Arguments
Use a for
loop to process all arguments dynamically.
Example:
Execution:
Output:
Checking Argument Count
You can ensure the script has the required number of arguments before proceeding.
Example:
Execution:
Output:
Handling Flags and Options
Flags or options are common in command-line tools (e.g., -h
, --help
). These can be implemented in Bash using a while
loop.
Example:
Execution:
Output:
Combining Arguments with Input Validation
Example: A Calculator Script
Execution:
Output:
Debugging Argument Handling
- Print All Arguments:
- Exit on Error:
- Enable Debugging:
Conclusion
Command line arguments make Bash scripts flexible and powerful. By using positional parameters, validation, and option handling, you can create scripts that adapt to a wide range of use cases.
Let me know if you'd like additional advanced examples!