Advanced while Read Patterns
Advanced while read
patterns extend beyond basic line reading, enabling sophisticated input validation, error handling, and data transformation in Bash scripting.
#!/bin/bash
## Robust input processing with multiple validations
process_data() {
local data="$1"
[[ -z "$data" ]] && return 1
[[ "$data" =~ ^[0-9]+$ ]] || return 1
echo "Valid input: $data"
}
while read -r input; do
process_data "$input" || {
echo "Invalid input: $input"
continue
}
done < input_stream.txt
Technique |
Description |
Use Case |
Field Separation |
Use IFS for complex parsing |
CSV/TSV files |
Regex Validation |
Pattern matching |
Data sanitization |
Error Handling |
Graceful input rejection |
Robust scripts |
Dynamic Stream Handling
#!/bin/bash
## Advanced stream processing with dynamic logic
process_stream() {
local count=0
local error_count=0
while read -r line; do
((count++))
process_line "$line" || ((error_count++))
done
echo "Processed $count lines, $error_count errors"
}
Processing Flow Visualization
graph TD
A[Input Stream] --> B{Read Line}
B --> C[Validate Input]
C --> |Valid| D[Process Line]
C --> |Invalid| E[Log Error]
D --> F{More Lines?}
E --> F
F --> |Yes| B
F --> |No| G[Finish]
Nested Loop and Complex Parsing
#!/bin/bash
## Nested processing with multiple conditions
while read -r user_data; do
while IFS=',' read -r name age role; do
[[ "$role" == "admin" ]] && {
echo "Admin user: $name"
## Additional admin processing
}
done <<< "$user_data"
done < user_database.txt
These advanced patterns demonstrate sophisticated input handling, enabling developers to create robust and flexible Bash scripts with comprehensive data processing capabilities.