Parameter Validation Methods
Introduction to Parameter Validation
Parameter validation ensures that script inputs meet expected criteria, preventing potential errors and improving script reliability.
Basic Validation Techniques
Checking Argument Count
#!/bin/bash
## Validate number of arguments
if [ $## -ne 2 ]; then
echo "Error: Exactly two arguments required"
echo "Usage: $0 <name> <age>"
exit 1
fi
Type Validation
#!/bin/bash
## Validate numeric input
if [[ ! $2 =~ ^[0-9]+$ ]]; then
echo "Error: Age must be a positive number"
exit 1
fi
Advanced Validation Methods
Regular Expression Validation
#!/bin/bash
## Email validation
validate_email() {
local email=$1
local regex="^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$"
if [[ ! $email =~ $regex ]]; then
echo "Invalid email format"
return 1
fi
}
validate_email "[email protected]"
Validation Strategies
Validation Type |
Description |
Example |
Presence Check |
Ensure parameter exists |
Check if argument is not empty |
Type Validation |
Verify input type |
Numeric, string, email |
Range Validation |
Check input boundaries |
Age between 0-120 |
Format Validation |
Match specific patterns |
Email, phone number |
Validation Workflow
graph TD
A[Receive Input] --> B{Presence Check}
B -->|Pass| C{Type Validation}
B -->|Fail| D[Reject Input]
C -->|Pass| E{Range Validation}
C -->|Fail| D
E -->|Pass| F{Format Validation}
E -->|Fail| D
F -->|Pass| G[Accept Input]
F -->|Fail| D
Comprehensive Validation Example
#!/bin/bash
validate_input() {
local name=$1
local age=$2
## Check argument count
if [ $## -ne 2 ]; then
echo "Error: Two arguments required"
return 1
fi
## Validate name (non-empty, alphabetic)
if [[ -z $name || ! $name =~ ^[A-Za-z]+$ ]]; then
echo "Invalid name: Must be non-empty alphabetic string"
return 1
fi
## Validate age (numeric, between 0-120)
if [[ ! $age =~ ^[0-9]+$ || $age -lt 0 || $age -gt 120 ]]; then
echo "Invalid age: Must be between 0-120"
return 1
fi
return 0
}
## Usage
validate_input "John" 30
Best Practices
- Validate early and comprehensively
- Provide clear error messages
- Use built-in test conditions
- Implement multiple validation layers
LabEx Scripting Considerations
In LabEx environments, robust parameter validation is crucial for creating reliable and secure shell scripts. Always anticipate and handle potential input variations.