Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • Prerequisites
  • Bash readarray
  • Bash readarray Examples
  • 2. From command output
  • Conclusion

Bash readarray with Examples

PreviousBash Loop Through Lines in a FileNextBash let with Examples

Last updated 1 year ago

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 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:

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/bashreadarray -t myArr < sample.txtecho ${myArr[0]} #Index 0 of the array will contain the first line of sample.txtecho ${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.

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/bashreadarray -t myArr < <(seq 5)echo ${myArr[0]} #Index 0 of the array will contain 1echo ${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.

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/bashreadarray myArr <<< $(cat sample.txt)echo ${myArr[0]} #Index 0 will contain the line till the first character ‘n’ is foundecho ${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.

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/bashreadarray -d “n” myArr < sample.txtecho ${myArr[0]} #Index 0 will contain the line till the first character ‘n’ is foundecho ${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.

5. Accessing Array Elements in Bash readarray

Example:

#!/bin/bashreadarray -t myArr < sample.txtecho ${myArr[0]} #Index 0 of the array will contain the first line of sample.txtecho ${myArr[1]} #Index 1 of the array will contain the second line of sample.txtecho ${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 $idoneecho "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..

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.

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.

file descriptor
Bash arrays
output of script - readarray from command output
output of script - readarray accessing array elements
output of script - readarray reading line from standard input
output of script - readarray reading from a file
sample file to read from
output of script - readarray delimeters