Bash Argument Basics
Understanding Command Line Arguments in Shell Scripting
Command line arguments are essential inputs passed to bash scripts during execution, enabling dynamic and flexible shell programming. In bash scripting, these arguments are automatically stored in special variables that allow developers to process and interact with user-provided data.
When executing a bash script, arguments are accessed through predefined variables:
Variable |
Description |
$0 |
Script name itself |
$1, $2, $3 |
First, second, third arguments |
$## |
Total number of arguments |
$* |
All arguments as a single string |
$@ |
All arguments as separate strings |
Code Example: Basic Argument Handling
#!/bin/bash
## Check total number of arguments
if [ $## -eq 0 ]; then
echo "No arguments provided"
exit 1
fi
## Access individual arguments
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "Total arguments: $#"
## Iterate through all arguments
for arg in "$@"; do
echo "Argument: $arg"
done
Argument Validation and Error Handling
Robust bash scripting requires validating and managing command line arguments:
#!/bin/bash
## Validate argument count
if [ $## -ne 2 ]; then
echo "Error: Exactly two arguments required"
exit 1
fi
## Type and format validation
if [[ ! "$1" =~ ^[0-9]+$ ]]; then
echo "First argument must be a number"
exit 1
fi
Workflow of Argument Processing
graph TD
A[Script Execution] --> B{Arguments Provided?}
B -->|Yes| C[Parse Arguments]
B -->|No| D[Display Error]
C --> E[Validate Arguments]
E --> F[Process Arguments]
E --> G[Handle Errors]