Bash Read File line by line

To Read File line by line in Bash Scripting, following are some of the ways explained in detail.

Example 1 – Read File Line by Line Using While Loop

Following is the syntax of reading file line by line in Bash using bash while loop.

Syntax

while read line; do    
    # line is available for processing
    echo $line    
done < fileName

Input File

Learn Bash Scripting.
Welcome to TutorialKart!
Learn Bash with examples.

Bash Script File

#!/bin/sh

i=1

while read line; do    
    # line is available for processing
    echo Line $i : $line    
    i=$(( i + 1 ))
done < sampleFile.txt

Output

~/workspace/bash/file$ ./read-file-line-by-line 
Line 1 : Learn Bash Scripting.
Line 2 : Welcome to TutorialKart!
Line 3 : Learn Bash with examples.
ADVERTISEMENT

Example 2 – Read File Line by Line Preventing Backslash Escapes

To prevent backslash escapes while reading file line by line in bash, use -r option of read command.

Syntax

while read -r line; do    
    # line is available for processing
    echo $line    
done < fileName

Bash Script File

#!/bin/sh

i=1

while read -r line; do    
    # line is available for processing
    echo Line $i : $line    
    i=$(( i + 1 ))
done < sampleFile.txt

Output

~/workspace/bash/file$ ./read-file-line-by-line 
Line 1 : Learn Bash Scripting.
Line 2 : Welcome to TutorialKart!
Line 3 : Learn Bash with examples.

Example 3 – Prevent Trimming Leading or Trailing Whitespaces

To prevent trimming of leading or trailing white-spaces while reading file line by line in bash, use IFS command in conjunction with read command :

Syntax

while IFS= read line; do    
    # line is available for processing
    echo $line    
done < fileName

Bash Script File

#!/bin/sh

i=1

while IFS= read line; do    
    # line is available for processing
    echo Line $i : $line    
    i=$(( i + 1 ))
done < sampleFile.txt

Output

~/workspace/bash/file$ ./read-file-line-by-line 
Line 1 : Learn Bash Scripting.
Line 2 : Welcome to TutorialKart!
Line 3 : Learn Bash with examples.

Conclusion

In this Bash Tutorial, we have learnt to read a file line by line in bash scripting with examples.