mapfile

Reads lines from standard input and assigns them to an array.

Summary

mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]

The main purpose

Options

-d delim sets delim as the line delimiter instead of the default newline character.
-n count Get at most count lines from standard input, or all if count is zero.
-O origin starts assigning values from the array index position origin, and the default index is 0.
-s count Skip reading the first count lines.
-t Remove line delimiter delim when reading (default is newline).
-u fd Read from file descriptor fd.
-C callback Call the callback statement whenever a quantum row is read.
-c quantum sets the number of lines to be read to quantum.

If -C is used without specifying a quantum value using -c, the quantum defaults to 5000.
When the callback statement is executed, the next index of the array to be assigned and the row to be read are passed to the callback statement as additional parameters.
If no starting position is provided when using -O, mapfile will clear the array before the actual assignment.

Parameters

array (optional): Array name to use for output. If no array name is specified, it will be written to the array named MAPFILE by default.

return value

Returns successful unless an illegal option is used, the specified array is read-only, or the specified array is not a subscripted array.

example

# Common reading forms.
mapfile < source_file target_array
cat source_file |mapfile target_array
mapfile -u fd target_array

# Read only the first 5 lines.
mapfile < source_file -n 5 target_array

# Skip the first 5 lines.
mapfile < source_file -s 5 target_array

#Start assigning values at the specified index in the array.
# Please note: doing this will not clear the array.
mapfile < source_file -O 2 target_array

# Set the line separator to tab when reading.
# Note that the tab in the second line needs to be entered using ctrl+v tab in the terminal;
mapfile < source_file -d $'\t' target_array
mapfile < source_file -d ' ' target_array

# Remove line separators (tabs) when reading.
mapfile < source_file -d $'\t' -t target_array
# Remove line separators (newlines) when reading.
mapfile < source_file -t target_array

# Every time 2 lines are read, a statement (echo in this case) is executed.
mapfile < source_file -C "echo CALLBACK:" -c 2 target_array

# Traverse the subscripts and display the elements of the array in sequence.
for i in ${!target_array[@]}; do
   printf "%s" ${target_array[i]}
done

Notice