The readarray
command in Bash is used to read lines from standard input into an indexed array. This is particularly useful when you want to store multiple lines of text or data into a single variable for further processing.
The basic syntax of the readarray
command is as follows:
readarray [options] [array_name]
-n N
: Read only the first N lines.-s N
: Skip the first N lines before reading.-t
: Remove the trailing newlines from each line read.-O N
: Specify the index to start storing the lines in the array.To read lines from a file into an array:
readarray my_array < my_file.txt
You can also read lines from the output of a command:
readarray my_array < <(ls -1)
To skip the first line of a file and read the rest into an array:
readarray -s 1 my_array < my_file.txt
To read lines from a file and remove trailing newlines:
readarray -t my_array < my_file.txt
To start storing lines in an array from a specific index:
readarray -O 5 my_array < my_file.txt
-t
option to avoid issues with trailing newlines when processing the array.echo "${my_array[@]}"
.readarray
with other commands like grep
or awk
for more powerful data manipulation.