Why file I/O is core to scripting in Bash Scripting - Performance Analysis
File input and output (I/O) is a key part of many scripts. Understanding how the time to read or write files grows helps us write better scripts.
We want to know how the script's running time changes as the file size changes.
Analyze the time complexity of the following code snippet.
#!/bin/bash
filename="$1"
while IFS= read -r line
do
echo "$line"
done < "$filename"
This script reads a file line by line and prints each line to the screen.
- Primary operation: Reading each line from the file one by one.
- How many times: Once for every line in the file.
As the file gets bigger, the script reads more lines, so it takes longer.
| Input Size (lines) | Approx. Operations |
|---|---|
| 10 | 10 reads and prints |
| 100 | 100 reads and prints |
| 1000 | 1000 reads and prints |
Pattern observation: The time grows directly with the number of lines. Double the lines, double the work.
Time Complexity: O(n)
This means the script's running time grows in a straight line with the file size.
[X] Wrong: "Reading a file line by line is always instant, no matter the size."
[OK] Correct: Larger files have more lines, so the script must do more work, which takes more time.
Knowing how file reading scales helps you explain script performance clearly. This skill shows you understand how scripts handle real data sizes.
"What if we read the whole file at once instead of line by line? How would the time complexity change?"