Apple's "Bash Script File Line Counter" interview question challenges candidates to write a Bash script that accurately counts lines in files, often emphasizing edge cases like large files, varying line endings, or multiple inputs. It tests Bash scripting proficiency, Linux utilities (e.g., wc, awk), and infrastructure-related handling of filesystems.[1][5]
Write a Bash script that takes one or more file paths as arguments and outputs the total number of lines across all files. The script must:
Basic Usage:
$ ./line_counter.sh file1.txt file2.txt Total lines: 42
file1.txt (5 lines), file2.txt (37 lines).Single File Example:
$ ./line_counter.sh sample.txt Total lines: 10
sample.txt content:
`
Line 1
Line 2Line 4 ... ` Counts 10 lines, including any blank ones.[3][5]
Edge Case (Empty File):
$ ./line_counter.sh empty.txt Total lines: 0
Multiple Files with Errors:
$ ./line_counter.sh *.log nonexistent.txt Error: nonexistent.txt: No such file Total lines: 150
Script should skip missing files gracefully.[4]
Common efficient solution using wc:
#!/bin/bash total=0 for file in "$@"; do if [[ -f "$file" ]]; then total=$((total + $(wc -l < "$file"))) else echo "Error: $file: No such file" >&2 fi done echo "Total lines: $total"
This avoids forking wc per byte count for better performance on large inputs.[9][5]