Read Lines Into an Array With mapfile
Load a file into a bash array without a read loop.
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
!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
- bash.1.en.html manual pageEvidence: The bash manual page documents mapfile.
Last verified: 2026-10-13 · Category: Developer