•5 min read

Bash Read File Line by Line: My Loop Wasn't Slow, My Shell Was

Last Thursday I needed every 404 path out of an 82MB nginx log. My first script read the file line by line in bash and piped each one into grep. Two minutes in it had done maybe forty thousand lines, so I killed it and blamed the loop.

It wasn't. Stripped down to a bare count, the loop finished a million lines in 38 seconds. Slow, sure. Not fifty-minutes slow.

Then I reached for mapfile, the fix every post recommends, and got mapfile: command not found. The bash on this laptop is 3.2.57, and Apple has not shipped a newer major version since 2007.

One file, six ways to read it

An 82MB access log, exactly 1,000,000 lines, macOS 26 on Apple silicon, two shells: the stock /bin/bash at 3.2.57 and bash 5.3.0 compiled from source. Best of two runs each.

MethodTimePeak RSS
wc -l0.08s2.7MB
awk '/404/'2.20s1.8MB
while read, bash 5.34.96s3.1MB
mapfile -t, whole file0.27s132MB
mapfile -t -n 10000, chunks0.27s4.4MB
while read, bash 3.237.99s2.8MB
Row of stainless steel ticket gates at a station entrance, each with an Entry arrow and a card reader
One at a time, in order. Fine for a person, expensive at a million.

Same script, character for character. 37.99 seconds against 4.96, decided entirely by which binary ran it.

The shell was the slow part

The bash 3.2 line shipped in 2007. Apple froze it for licensing reasons and never went back, so 3.2.57 is still what you get when you type bash on a clean Mac. /bin/sh is bash 3.2 too, just in POSIX mode:

$ bash --version | head -1
GNU bash, version 3.2.57(1)-release (arm64-apple-darwin26)

$ sh -c 'echo $BASH_VERSION'
3.2.57(1)-release

mapfile only exists from bash 4.0 onward, so the 3.2 row is doing all of that with the older read: find the delimiter, copy the bytes, run the body, repeat a million times.

mapfile is fast, and it costs 132 megabytes

The speed claim holds. 0.27 seconds against 4.96 is not a rounding error.

The memory claim does not. Reading 82MB into an array peaks bash at 132MB, because every line becomes its own string with its own header and allocation. It gets sold as the efficient choice because it skips the pipe, which it does, then holds the whole file in RAM.

Which is what the chunked row is for: same 0.27 seconds, 4.4MB of peak, because at most ten thousand lines exist at once. The peak follows the chunk size, not the file size.

The chunked loop that never exits

This is where I lost an afternoon. The chunked pattern looks correct:

while mapfile -t -n 10000 chunk; do
  process "${chunk[@]}"
done < access.log

Run it against a million lines and it spins at 100% CPU. Not slowly. Forever.

Because mapfile returns success whether or not it read anything. I watched it hand back a zero-element array and exit 0 over and over, then went to the source: the last statement of mapfile() in builtins/mapfile.def is return EXECUTION_SUCCESS, and nothing above it returns anything else. No EOF failure path at all. bash 5.3.0 is what I tested, and it loops forever on an empty file too, which is how I believed it.

One more condition fixes it:

while mapfile -t -n 10000 chunk && [ ${#chunk[@]} -gt 0 ]; do
  process "${chunk[@]}"
done < access.log

Without it you have an infinite loop that reads fine in review, and in CI it burns a core until the job times out complaining about something else.

read does the right thing here: at EOF it returns 1, and that non-zero status is the whole reason while read terminates. mapfile broke the contract, and the snippet got copied anyway.

Forking once per line and nothing else matters

My original script piped every line into grep:

while IFS= read -r line; do
  printf '%s\n' "$line" | grep -q ' 404 ' && hits=$((hits + 1))
done < access.log

Ten thousand lines took 30.55 seconds under bash 5.3, 31.30 under bash 3.2. Two forks per line, 18.8 of those seconds in system time, which is the kernel building and tearing down processes.

Swap the pipe for a builtin match and the same ten thousand take 0.05 seconds:

case $line in
  *' 404 '*) hits=$((hits + 1)) ;;
esac

Six hundred times faster, and the shell version stops mattering entirely. At 30.55 seconds per ten thousand lines, my first attempt was a fifty-minute job in a fast script's clothes. I killed it at two minutes on instinct.

If you need a command per line, stop paying per line. Hand the file to awk, or split it and run the pieces in parallel as in the xargs -P post.

The traps that still bite

These I re-checked here.

A file that does not end in a newline loses its last line, since read returns non-zero on that final chunk. Three lines, the third unterminated: two iterations. Adding || [ -n "$line" ] got all three.

IFS= and -r are separate fixes and you want both. IFS= read line without -r kept two leading spaces intact and still turned C:\logs\api into C:logsapi. One of two looks like it worked, which is worse than neither.

Pipes still run the loop body in a subshell, so a counter set inside cat file | while read came out as 0 afterwards. On bash 5, shopt -s lastpipe fixes that and the same script reports 2; on bash 3.2 the option does not exist. Under set -e a bare read outside a loop exits the script on an empty stream, the same class of trap as the grep case in the strict mode post.

What is new, at least to me, is how much of that advice depends on a version number nobody prints.

So: awk when the job is really text munging, and while IFS= read -r when it is shell logic per line, on a bash I have printed the version of. When I do need the lines as an array I chunk them and guard the loop, and that guard lives in Snippet Ark, because I keep forgetting it and keep rediscovering it at 100% CPU.