Open In App

mapfile Command in Linux With Examples

mapfile also called (read array) is a command of the Bash shell used to read arrays. It reads lines from the standard input into an array variable. Also, mapfile must read from substitution (< <) and not from a pipe. Also, mapfile is faster and more convenient when compared to a read loop. It returns 1 or 0 depending on whether the command was successful or not. If no array name is not specified, the default variable MAPFILE is used as the target array variable.

Syntax: mapfile [array]



Alternatively, we can use read array [arrayname] instead of mapfile.

Example 1. Reading an array from a file:



$ mapfile MYFILE < example.txt
$ echo ${MYFILE[@]}
$ echo ${MYFILE[0]}

Output:

Example 2. Capture the output into an array:

$ mapfile GEEKSFORGEEKS < <(printf "Item 1\nItem 2\nItem 3\n")
$ echo  ${GEEKSFORGEEKS[@]}

Here, Item1, Item2, and Item 3 have been stored in the array GEEKSFORGEEKS.

Output:

Example 3. Strip newlines and store item using -t:

$ mapfile -t GEEKSFORGEEKS< <(printf "Item 1\nItem 2\nItem 3\n")
$ printf "%s\n" "${GEEKSFORGEEKS[@]}"

Output:

Example 4. Read the specified number of lines using -n:

$ mapfile -n 2 GEEKSFORGEEKS < example.txt
$ echo  ${GEEKSFORGEEKS[@]}

It reads at most 2 lines. If 0 is specified then all lines are considered.

Output:

Article Tags :