Open In App

mapfile Command in Linux With Examples

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The 'mapfile' command, also known as 'readarray', is a powerful built-in feature of the Bash shell used for reading input lines into an array variable. Unlike using a loop with read, mapfile reads lines directly from standard input or command substitution (< <(command)) rather than from a pipe, making it faster and more convenient for handling arrays. If no array name is provided, 'mapfile' defaults to using the variable MAPFILE to store the data.

What does the 'mapfile' Command do?

The 'mapfile' command is particularly useful when you need to read data line by line into an array, allowing you to manipulate each line individually or collectively with ease. This command is especially beneficial when dealing with data processing, file reading, and output capturing tasks in scripts.

Syntax: mapfile [array]

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

mapfile Command Examples in Linux

Example 1. Reading an array from a file:

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

Output:

mapfile command in Linux with examples

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:

mapfile command in Linux with examples

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:

mapfile command in Linux with examples

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:

mapfile command in Linux with examples

Conclusion

The mapfile command in Bash is a useful tool for reading lines into arrays from standard input or command substitution. It makes handling data in scripts easier by eliminating the need for loops and provides various options for managing input, like stripping newlines, reading a set number of lines, or using callbacks for processing. Mapfile and its options can enhance your data handling capabilities in Bash, leading to more powerful and flexible scripting.


Article Tags :

Similar Reads