Collect lines into arrays
Use mapfile -t lines < input.txt (also named readarray) to collect text records in an indexed array. -t removes each trailing record delimiter, normally a newline; empty lines become empty elements and a final nonempty unterminated line is retained. By default mapfile clears the destination before reading; -O can select an explicit origin instead. It loads the collected data into memory, so a streaming while/read loop is better for large or unbounded input. Bash 4+ is required for mapfile. For fields on one line use read -r -a fields: it splits according to IFS, not shell quoting or CSV rules, and clears existing array elements first. Use process substitution or input redirection instead of a pipeline if you need the array in the current shell. NUL-delimited input is a separate format; do not capture NUL in a variable. In Bash 5.2 mapfile -d with an empty delimiter can collect NUL-terminated records; each stored element excludes the delimiter with -t. Producer failure needs separate handling, as learned in Chapter 9. An explicit origin with -O does not clear other existing elements. A final nonempty record without a NUL delimiter can also be retained by mapfile; success alone does not establish complete framing or producer success. Example 1 guards file creation and collection before reporting.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Collect complete and partial lines
printf 'daily report\n\nlast' > input.txt &&mapfile -t lines < input.txt &&printf 'count=%s\n' "${#lines[@]}" &&for line in "${lines[@]}"; do printf '[%s]\n' "$line"; doneExpected stdout:
count=3[daily report][][last]Spaces, the blank line and the last partial line survive.
Split one line into fields
read -r -a fields < <(printf '%s\n' 'red green blue')printf 'count=%s\n' "${#fields[@]}"printf '[%s]\n' "${fields[@]}"Expected stdout:
count=3[red][green][blue]Default IFS treats runs of spaces as separators, rather than preserving a whole line.
Collect NUL-delimited records
mapfile -d '' -t names < <(printf '%s\0' 'daily report' $'two\nlines')printf 'count=%s\n' "${#names[@]}"printf '%q\n' "${names[@]}"Expected stdout:
count=2daily\ report$'two\nlines'The newline inside a record survives; %q makes it visible.
Common mistakes
Do not use items=($(cat file)) to collect lines. Command substitution and unquoted splitting change boundaries and discard empty lines. Do not use read -a for general CSV parsing.
Practice
Create a three-record text file with a spaced line, a blank line and an unterminated last line. Collect and count them with mapfile -t. Separately split one whitespace-delimited line using read -r -a and compare the results.
Next: Functions, scope and modularity