Bash readarray with Examples

Written by: Linuxopsys   |   Last updated: March 24, 2023

In every programming language, the term array means a collection of items that holds some data. The data would be in an indexed manner. 

The unique property bash array is that it can save different types of elements. In this tutorial, we are going to learn about readarray.

Prerequisites

  • A text editor 
  • Access to a terminal

Bash readarray

From Bash version 4, storing the contents in an array has become straightforward. Now you can easily read contents into the array. The readarray utility simply read lines from the standard input into the indexed array.  It can also be read from the file descriptor by making use of the -u flag. The output is passed to the readarray command which, in turn, reads those contents and stores them in the array.

Here’s the syntax:

readarray [-d delimiter] [-n count] [-O origin] [-s count] [-t] [-u fd] myArr

where,

-d delimiter: Specifies a delimiter character to use instead of the newline character.

-n: Copy at most the specified number of lines. All the lines are copied if the count is set to 0.

-O: Assigning to the array at index origin. By default the index kept 0.

-s: Let go of the first count lines read.

-t: Remove a trailing delimiter from each line read. The default value is a newline.

-u: Read lines from file descriptor fd instead of the standard input.

myArr: Name of the array to be declared.

Bash readarray Examples

Populating the array using the readarray command can be done either by reading the file, the command output or the standard input.

1. Reading from a File

Let’s assume there is a sample.txt file that with the following contents:

sample file to read from

While reading from a file, the ‘<’ symbol will first redirect the standard input to sample.txt and then the array will be created based on the contents of the file.

Example:

#!/bin/bash
readarray -t myArr  < sample.txt	
echo ${myArr[0]}	#Index 0 of the array will contain the first line of sample.txt
echo ${myArr[1]}	#Index 1 of the array will contain the second line of sample.txt

The file sample.txt is simply fed to the readarray command. Each line of the file is stored in the array myArr. 

output of script - readarray reading from a file

2. From command output

In this case, the output of any command is passed as an input to the readarray command. The input is then stored in the declared array.

Example:

#!/bin/bash
readarray -t myArr < <(seq 5)
echo ${myArr[0]}	#Index 0 of the array will contain 1
echo ${myArr[1]}	#Index 1 of the array will contain 2

The < <(seq 5) redirects its output to the standard input. The process substitution <(seq 5) is redirecting the output of ‘seq 5’ to the standard input.This makes the output of the command appear like a file. Redirecting this file to readarray is done using the first redirection operator (<). Thus, the readarray command can read the output of the command and populate the array.

output of script - readarray from command output

3. Reading line from standard input 

Here, the input from the standard input is read by the readarray utility. This is then stored in the array variable defined. 

Example:

#!/bin/bash
readarray myArr  <<< $(cat sample.txt)
echo ${myArr[0]}	#Index 0  will contain the line till the first character ‘n’ is found
echo ${myArr[1]}	#Index 1 will contain after the first ‘n’ till the second ‘n’ is found

This method makes use of a here string to supply the contents of the file as a standard input to the readarray command. The lines from the standard input fill the indexed array.

output of script - readarray reading line from standard input

4. Working with Delimiters

The readarray command can take a delimiter symbol which indicates the beginning or the end of a data item. With this feature, one can decide when the next element of the array is to be populated.

Example:

#!/bin/bash
readarray -d “n” myArr  < sample.txt
echo ${myArr[0]}	#Index 0  will contain the line till the first character ‘n’ is found
echo ${myArr[1]}	#Index 1 will contain after the first ‘n’ till the second ‘n’ is found

The delimiter in this example is the character ‘n’. The number of elements in the array will depend on the number of times the character ‘n’ appears in the sample.txt file. The readarray command will keep on adding data to that particular array element until the delimiter character ‘n’ is not found. The moment it finds ‘n’ in the file, it will increment the array index and assign data from the next character onwards, until the next ‘n’ is not found. This process will continue until the end of the file.

output of script - readarray delimeters

5. Accessing Array Elements in Bash readarray 

Bash arrays can be referenced using the index number. Each element of the array can also be accessed using a loop. Furthermore, all the array elements can be accessed together in one go. Bash also gives the option to access the array elements from a particular element. 

Example:

#!/bin/bash
readarray -t myArr  < sample.txt
echo ${myArr[0]}	#Index 0 of the array will contain the first line of sample.txt
echo ${myArr[1]}	#Index 1 of the array will contain the second line of sample.txt
echo ${myArr[4]}	#Index 4 of the array will contain the fifth line of sample.txt

echo "-----------------Printing values using a loop-------------------"
echo "Method 1:"
for i in ${myArr[@]}
do
	echo $i
done
echo "Method 2:"
for (( i=0; i<${#myArr[@]}; i++ ))
do
    echo ${myArr[$i]}
done

echo "-----------------Printing all the values-------------------"
echo "Method 1:"
echo ${myArr[*]}
echo "Method 2:"
echo ${myArr[@]}

echo "-----------------Printing values from a particular index say 3-------------------"
echo "Method 1:"
echo ${myArr[*]:3}
echo "Method 2:"
echo ${myArr[*]:3}

Assuming the array myArr has been populated, the array elements can be accessed using their indexes. The default index of an array is numeric. The echo command will display each array value individually. 

The array can be iterated over a loop as well and individual elements can be referenced using the iterator.

The entire array can be printed using a single echo command by referencing the array index with the “*” or “@” symbol. 

The array elements can be displayed from a particular starting index as well..

output of script - readarray accessing array elements

Conclusion

Take away points we learned here:

  • The Bash readarray utility is a simple, single line command for storing data in the form of an array.
  • The output of any command is fed as an input to the array, thereby populating it.
  • The contents of a file can be stored in an array directly, too.
  • The array elements can be effectively accessed using the index numbers.
SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment