Bash: How to Read Lines of File into Array


Often you may want to use Bash to read the lines from a particular file into an array.

The easiest way to do so is by using the readarray command with the following basic syntax:

readarray -t my_array < my_file.txt

This particular example reads all of the lines from the file named my_file.txt in the current directory into an array named my_array.

The -t command specifies that any newline characters should be stripped away.

Once you’ve read the file into an array, you can view all elements of the array by using the following syntax:

for value in "${my_array[@]}"; do
    echo "$value"
done

You can also access specific elements of the array by using the following syntax:

echo "${my_array[2]}"

This particular example will return the third line from the file.

Note: The first element of an array in Bash has an index value of 0.

The following example shows how to use the readarray command to read the lines of a file into an array in practice.

Example: How to Read Lines of File into an Array in Bash

Suppose that we have a file in our current directory named teams.txt.

We can use the cat statement to view the contents of this file:

This file contains the names of various professional basketball teams.

We can use the following syntax to read each of the lines from this file into an array named my_array:

readarray -t my_array < teams.txt

The following screenshot shows how to use this syntax in practice:

Bash read lines from file into array

Since we don’t receive any error messages, we can assume that the lines from the file were successfully read into the array.

We can use the following syntax to view all of the contents of the array named my_array:

for value in "${my_array[@]}"; do
    echo "$value"
done

The following screenshot shows how to use this syntax in practice:

We can see that the array named my_array does indeed contain all of the contents from the teams.txt file.

We can use the following syntax to access the third element in the array:

echo "${my_array[2]}"

The following screenshot shows how to use this syntax in practice:

We can see that this element of the array contains the third line from the file.

We can use similar syntax to access any line from the file that we would like.

Note: You can find the complete documentation for the readarray command in Bash here.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Read Columns from CSV File into Arrays
Bash: How to Read CSV File and Skip First Line
Bash: How to Count Number of Columns in File

Leave a Reply