mapfile – Reads lines from standard input and assigns them to an array

The mapfile command in Linux is used to read lines from standard input and assign them to an array variable. This command is useful when you want to read a file or output from a command and store it in an array for processing.

Overview

The syntax for mapfile command is as follows:

mapfile [-n count] [-O origin] [-t] [-u fd] [-C callback] [-c quantum] [array]
  • The -n option specifies the number of lines to read from standard input.
  • The -O option specifies the index from which the array elements should be assigned.
  • The -t option removes the newline character from the end of each line.
  • The -u option specifies the file descriptor from which to read input.
  • The -C option specifies a callback function to be executed after each line is read.
  • The -c option specifies the number of lines to read at a time (quantum).

If no array name is specified, the mapfile command will use the default array name MAPFILE.

Examples

  1. Read lines from a file and store them in an array:
$ cat file.txt | mapfile myarray
  1. Read lines from a file and remove the newline character from the end of each line:
$ cat file.txt | mapfile -t myarray
  1. Read the first 5 lines from a file and store them in an array:
$ head -n 5 file.txt | mapfile -n 5 myarray
  1. Read lines from a file and execute a callback function after each line is read:
$ cat file.txt | mapfile -C 'echo "Line read: $line"' myarray

Options

The following table lists the available options for the mapfile command:

Option Description
-n count Specifies the number of lines to read from standard input.
-O origin Specifies the index from which the array elements should be assigned.
-t Removes the newline character from the end of each line.
-u fd Specifies the file descriptor from which to read input.
-C callback Specifies a callback function to be executed after each line is read.
-c quantum Specifies the number of lines to read at a time (quantum).

Troubleshooting tips

  • If you encounter an error message that says “mapfile: command not found”, it means that the mapfile command is not installed on your system. You can install it by running the following command:
$ sudo apt-get install bash-builtins
  • If you encounter an error message that says “mapfile: array name must be a valid identifier”, it means that the array name you specified is not valid. Array names must start with a letter or underscore and can only contain letters, numbers, and underscores.

Notes

  • The mapfile command is only available in Bash version 4 or later. If you are using an older version of Bash, you can use the readarray command instead, which has the same functionality as mapfile.
  • By default, mapfile uses the newline character as the delimiter to separate lines. If you want to use a different delimiter, you can set the IFS (Internal Field Separator) variable to the desired value before running the mapfile command.