Read arrays and mapfile overview
An indexed array is a variable that can hold multiple numbered elements. This lesson previews just enough syntax to read input; indexing and array manipulation are taught later. read -r -a items splits one record into array elements using IFS. mapfile -t lines collects input records into an indexed array, preserving spaces within each line and removing the newline delimiter with -t. An unterminated final record is retained by mapfile -t; an empty input file produces zero elements, while a newline-only file produces one empty element. readarray is a synonym. mapfile and readarray are Bash features available from Bash 4.0, not POSIX sh. "${lines[@]}" forwards each element as a distinct argument and ${#lines[@]} counts elements. For large or unbounded input prefer streaming rather than loading everything into memory; a later loops chapter teaches that pattern.
Practical examples
Run each example separately in Bash 5.2 in a fresh empty practice directory, using default shell options and C locale. Output is shown separately; do not enter it as code.
One line into fields
printf '%s\n' 'red green blue' > input.txtread -r -a items < input.txtprintf 'count=%s\n' "${#items[@]}"printf '[%s]\n' "${items[@]}"Expected stdout:
count=3[red][green][blue]Expected stderr:
No output
Overall example exit status: 0
The single record is split into three fields.
Collect full records
printf '%s\n' 'red green' '' 'blue' > input.txtmapfile -t lines < input.txtprintf 'count=%s\n' "${#lines[@]}"printf '[%s]\n' "${lines[@]}"Expected stdout:
count=3[red green][][blue]Expected stderr:
No output
Overall example exit status: 0
Spaces and the empty record are retained as array elements.
Limit collection
printf '%s\n' one two three > input.txtreadarray -t -n 2 lines < input.txtprintf 'count=%s\n' "${#lines[@]}"printf '%s\n' "${lines[@]}"Expected stdout:
count=2onetwoExpected stderr:
No output
Overall example exit status: 0
The -n 2 option limits collection to two records.
Common mistakes
read -a does not collect every line. mapfile without -t retains delimiters where present. Do not unquote "${lines[@]}" or rely on printf with no data arguments to prove an array is nonempty; check its length.
Practice
Collect three records, including a blank line and a line with spaces, using mapfile -t. Print the element count and each record in brackets.
Next: Exit status, true, false and exit