LinuxCommandLibrary

mapfile

Read lines from stdin into a bash array

TLDR

Read file into array
$ mapfile [array] < [file.txt]
copy
Read with line limit
$ mapfile -n [10] [array] < [file.txt]
copy
Skip first N lines
$ mapfile -s [2] [array] < [file.txt]
copy
Remove trailing newlines
$ mapfile -t [array] < [file.txt]
copy
Use specific delimiter
$ mapfile -d ':' [array] < [file.txt]
copy
Read from command
$ mapfile [array] < <(ls)
copy

SYNOPSIS

mapfile [options] [array]

DESCRIPTION

mapfile (also known as readarray) is a bash builtin that reads lines from standard input into an indexed array variable. Without a variable name, it uses the default array `MAPFILE`.
It is significantly faster than a `while read` loop for reading files into arrays, as it is implemented as a builtin rather than running in a subshell.

PARAMETERS

ARRAY

Array variable name.
-n COUNT
Maximum lines to read.
-s COUNT
Lines to skip.
-t
Remove trailing delimiters.
-d DELIM
Use delimiter instead of newline (bash 4.4+).
-O ORIGIN
Start assigning at array index ORIGIN (default: 0).
-C CALLBACK
Call CALLBACK after reading each line.
-c QUANTUM
Call CALLBACK every QUANTUM lines (default: 5000).

CAVEATS

Bash-specific builtin (bash 4.0+). Not available in sh or other POSIX shells. The `-d` option requires bash 4.4 or later. Cannot read from a pipe in a subshell context -- use process substitution (`< <(command)`) instead of piping (`command | mapfile`).

HISTORY

mapfile was added to Bash 4.0 (released 2009) as a builtin for efficiently reading files into arrays. The `-d` delimiter option was added in Bash 4.4.

SEE ALSO

read(1), bash(1)

> TERMINAL_GEAR

Curated for the Linux community

Copied to clipboard