![]() |
VOOZH | about |
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.
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 MYFILE < example.txt
$ echo ${MYFILE[@]}
$ echo ${MYFILE[0]}Output:
👁 mapfile command in Linux with examples$ 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$ mapfile -t GEEKSFORGEEKS< <(printf "Item 1\nItem 2\nItem 3\n")
$ printf "%s\n" "${GEEKSFORGEEKS[@]}"Output:
👁 mapfile command in Linux with examples$ 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 examplesThe 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.