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
  • 1. Using a while loop with read command
  • 2. Using a while loop with file descriptor
  • 3. Using a for loop with cat command
  • 4. Using a while loop with input redirection
  • 5. Using a while loop with IFS (Internal Field Separator)
  • Conclusion

Bash Loop Through Lines in a File

PreviousBash Function Return ValueNextBash readarray with Examples

Last updated 1 year ago

The most efficient way to process any file, one line at a time, is to develop a bash script and give the file as input to the script. This can be done by reading a file line by line by iterating the lines over a loop. Bash treats each line as an element in a list. Understanding how to process the contents of a large data file one line at a time saves us from constantly opening them. There are many ways of reading each line using Bash.

Prerequisites

  • A text editor (to create a text file to be read)

  • Access to a terminal

The first thing needed is to create a text file with the name sample.txt with the following contents:

1. Using a while loop with read command

while loop when used with the read utility will read each line from the file and in each step store the content of the line in the variable.

Here’s the syntax:

while read -r line
do
    echo "$line"
done < sample.txt

To create the script (script1.sh), open the terminal in your favorite editor, put the following contents and save it:

while read -r linedo echo "$line" #printing the line; perform any other operation on line variabledone < sample.txt

2. Using a while loop with file descriptor

Here’s the syntax:

while read -r -u5 line
do
    echo "$line"
done 5< sample.txt

Example:

while read -r -u5 linedo echo "$line" #printing the line; perform any other operation on line variabledone 5< sample.txt

3. Using a for loop with cat command

To display the contents of a file in individual lines, one can iterate over the for loop and make use of the Linux cat command. The for loop enables printing of the lines from the cat command output until the end of the file.

Here’s the syntax:

for line in $(cat sample.txt)
do
    echo "$line"
done

Example:

#!/bin/bashfor line in $(cat sample.txt)do echo "$line" #printing the line; perform any other operation on line variabledone

For each iteration, the for loop iterates over every line of the cat command output and stores it in the variable $line. It then prints the value stored in the variable using the echo command until it reaches the end of the file. The loop will stop after the last line has been processed.

4. Using a while loop with input redirection

Here’s the syntax of here string:

COMMAND <<< $VAR

Example:

#!/bin/bashwhile read -r linedo echo "$line" #printing the line; perform any other operation on line variabledone <<< $(cat sample.txt )

The here string supplies the output generated from the cat command as an input to the read command. In the loop this is read one line at a time and stored in the bash variable $line.

5. Using a while loop with IFS (Internal Field Separator)

To display the contents of a file in individual lines, one can iterate over the while loop with the Internal Field Separator. The IFS= argument is chosen as an empty string. This helps to preserve the whitespaces.

Here’s the syntax:

while IFS= read -r line
do
    echo "$line"
done < <(cat sample.txt)

Example:

#!/bin/bashwhile IFS= read -r linedo echo "$line" #printing the line; perform any other operation on line variabledone < <(cat sample.txt)

This technique is also known as process or command substitution which runs a bash command and stores its output in a variable or passes it to another command. Here, the standard output of the process is available as a file which in turn is fed into the standard input of another process. The input file is supplied and each line is printed separately.

Conclusion

  • There are multiple ways of reading a file one line at a time using loops in bash.

  • Reading a file line by line becomes important when it is huge and certain keywords need to be searched in real-time.

  • Reading an entire file in one go can slow down the process as compared to reading it line by line because nothing is processed until the read is complete.

For each iteration of the , the read command reads that particular line of the file and assigns it to the bash shell variable $line. The loop runs till the number of lines in the file. After reading the last line of the file, the while loop stops. The -r flag of the read command prevents the interpretation of any backslash-escaped characters while reading.

A file descriptor is an unsigned integer used by a Linux process to uniquely identify an . A minimum of one file descriptor exists for every open file. The first three , by default, are STDIN (0), STDOUT (1), and STDERR (2).

For each iteration of the while loop, the command reads input from a file descriptor specified by the -u argument and the file descriptor number. The input file's contents are sent to the specified file descriptor. It is always advised to use a number between 4 and 9 to avoid conflict with the internal shell file descriptors.

This method makes use of a here string to supply the contents of the file to the read command. Here String is used for input from a string, a file or a variable. It is constructed using the <<< operator to redirect a string into a command.

while loop
open file
file descriptors
read
redirection
while loop input redirection - script output
for loop with cat - output of the script
file while read - output of the script
sample file with lines
while loop IFS output of the bash script
while loop file descriptor - output of the script