Read Lines Into an Array With mapfile

Load a file into a bash array without a read loop.

macOSbashshellscriptingLow risk
Run mapfile -t lines < file.txt, then use "${#lines[@]}" for the count.

01Command

Command
$ mapfile -t lines < file.txt; echo "${#lines[@]}"

02What it does

mapfile slurps standard input into an indexed array in one call, which is faster and less error-prone than a while-read loop. It is the efficient primitive for processing line-oriented files in scripts.

03Risk

RiskLow risk
RequirementsmacOS default zsh/bash (bash 3.2+; some features need bash 4+ via Homebrew)
CompatibilitymacOS with bash 3.2+ (GNU bash 4+ via Homebrew for advanced features)
!Warning: The -t flag strips trailing newlines; omit it only when you need to preserve them.

04Undo

✓No undo needed — this command does not change persistent state.

05Sources

Last verified: 2026-10-13 · Category: Developer