LinuxCommandLibrary

mapfile

Read lines from standard input into array

TLDR

View documentation for the original command

$ tldr readarray
copy

SYNOPSIS

mapfile [options] [array]
readarray [options] [array]

PARAMETERS

-t
    Remove a trailing newline character from each line read.

-n count
    Read at most count lines. If count is 0, all lines are read.

-O origin
    Start assigning to array at index origin. Defaults to 0.

-s count
    Skip the first count lines read before assigning.

-u fd
    Read lines from file descriptor fd instead of standard input (stdin).

-d delimiter
    Use delimiter to terminate lines instead of the default newline character. The delimiter is not removed.

DESCRIPTION

The mapfile command, also known as readarray, is a Bash built-in that reads lines from standard input or a specified file descriptor into an indexed array variable. It's an efficient way to populate a Bash array, especially when dealing with line-oriented data. It allows for various options like skipping lines, limiting the number of lines read, removing trailing newlines, and specifying a custom delimiter.

This command is often preferred over traditional while read line loops for its performance benefits and conciseness when the goal is to load an entire file or stream into memory for further processing as an array. It simplifies tasks such as processing command output line-by-line or handling configuration files.

CAVEATS

  • mapfile is a Bash built-in command, not an external executable. This means it's part of the shell itself and its behavior might vary slightly between Bash versions.
  • Reading very large files into memory using mapfile can consume significant system resources, as the entire content is loaded into an array.
  • When a custom delimiter is used with -d, the delimiter itself is not removed from the line unless explicitly handled by the user.

DEFAULT BEHAVIOR

If no array name is specified, the command uses a default array named MAPFILE to store the lines.

RETURN STATUS

mapfile returns 0 unless an invalid option is encountered, an invalid file descriptor is specified, or the array variable is not a valid array name or is read-only.

COMMON USAGE

It is frequently used with process substitution or pipes, e.g., mapfile -t <(grep pattern file.txt) to get filtered lines, or ls -l | mapfile -t myArray to capture `ls` output.

HISTORY

The readarray built-in was introduced in Bash 4.0. The mapfile alias was added in Bash 4.0 as well, providing a more intuitive name for its primary function. Its development aimed to offer a more efficient and direct way to populate arrays from file or stream input, addressing common scripting patterns where line-by-line processing via while read loops could be less performant or verbose.

SEE ALSO

read(1), cat(1), awk(1), grep(1), printf(1)

Copied to clipboard