Input validation is crucial for creating robust and secure bash scripts. Effective validation ensures data integrity, prevents unexpected behavior, and enhances script reliability.
Validation Techniques and Patterns
| Validation Type | Regex Pattern | Description |
| --------------- | ---------------------------------------- | ------------------ | ------------------------------- | ----------- | ------------------- | --------------- |
| Numeric Input | ^[0-9]+$
| Integer validation |
| Email Format | ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z | a-z]{2,}$
| Email address check |
| IP Address | ^((25[0-5] | 2[0-4][0-9] | [01]?[0-9][0-9]?)\.){3}(25[0-5] | 2[0-4][0-9] | [01]?[0-9][0-9]?)$
| IPv4 validation |
Comprehensive Validation Script
#!/bin/bash
validate_input() {
local input="$1"
local type="$2"
case "$type" in
"number")
[[ "$input" =~ ^[0-9]+$ ]]
;;
"email")
[[ "$input" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$ ]]
;;
"ip")
[[ "$input" =~ ^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$ ]]
;;
*)
return 1
;;
esac
}
## Example usage
if validate_input "$1" "email"; then
echo "Valid email address"
else
echo "Invalid email address"
exit 1
fi
#!/bin/bash
validate_range() {
local value="$1"
local min="$2"
local max="$3"
if [[ "$value" =~ ^[0-9]+$ ]]; then
if ((value >= min && value <= max)); then
return 0
fi
fi
return 1
}
## Example: Validate age between 18 and 65
if validate_range "$1" 18 65; then
echo "Age is valid"
else
echo "Age must be between 18 and 65"
exit 1
fi
Validation Workflow
graph TD
A[Receive Input] --> B{Validate Type}
B -->|Numeric| C[Check Number Range]
B -->|String| D[Check Length/Format]
B -->|Complex| E[Apply Multiple Checks]
C --> F{Valid?}
D --> F
E --> F
F -->|Yes| G[Process Input]
F -->|No| H[Reject Input]
Advanced Validation with Error Handling
#!/bin/bash
process_input() {
local input="$1"
## Multiple validation checks
if [[ ! "$input" =~ ^[0-9]+$ ]]; then
echo "Error: Numeric input required" >&2
return 1
fi
if ((input < 0 || input > 100)); then
echo "Error: Value must be between 0 and 100" >&2
return 1
fi
## Additional custom validations can be added
echo "Input processed successfully: $input"
}
## Execute with error handling
if ! process_input "$1"; then
exit 1
fi