Problem Statement
Explain advanced loop patterns including nested loops, break/continue, loop control with signals, and reading files efficiently.
Explanation
Nested loops: loops inside loops, each with own iteration variable. Example:
```bash
for i in {1..3}; do
for j in {a..c}; do
echo "$i$j"
done
done
```
Produces combinations. Track depth carefully, use meaningful variable names. Break exits innermost loop, break N exits N levels of nested loops.
Break and continue: break exits loop entirely, continue skips remaining commands and starts next iteration. Use for early exit on conditions or skipping invalid data:
```bash
for file in *.txt; do
[ -r "$file" ] || continue # Skip unreadable files
process "$file"
done
```
Efficient file reading: avoid cat in loop (useless use of cat). Good: while read line; do echo "$line"; done < file. Bad: cat file | while read line. Process substitution: while read line; do ... done < <(command). Read multiple columns: while read col1 col2 col3; do ... done < file splits on whitespace.
Reading with IFS: while IFS=: read user pass uid gid; do echo "$user"; done < /etc/passwd splits on colons. Preserve whitespace: while IFS= read -r line ensures leading/trailing spaces kept, backslashes not interpreted. Handle last line without newline: while IFS= read -r line || [ -n "$line" ]; do ... done.
Loop optimization: minimize external commands in loops (slow), use built-ins when possible, process in batches for large datasets, consider awk/sed for text processing instead of loops. Monitor progress in long loops: ((count++ % 100 == 0)) && echo "Processed $count items". Understanding loop patterns enables efficient data processing.