0
0
Bash Scriptingscripting~5 mins

Reading files line by line (while read) in Bash Scripting

Choose your learning style9 modes available
Introduction

Reading a file line by line helps you process each line separately. This is useful when you want to handle big files or extract information step by step.

You want to count or analyze each line in a log file.
You need to extract specific data from a file line by line.
You want to automate tasks that depend on each line of a configuration file.
You want to read user input saved in a file and process it one line at a time.
Syntax
Bash Scripting
while IFS= read -r line; do
  # commands using "$line"
done < filename

IFS= prevents trimming leading/trailing spaces.

-r stops backslash escapes from being interpreted.

Examples
Reads each line and prints it. Simple but may trim spaces or interpret backslashes.
Bash Scripting
while read line; do
  echo "$line"
done < file.txt
Reads each line exactly as is, preserving spaces and backslashes.
Bash Scripting
while IFS= read -r line; do
  echo "$line"
done < file.txt
Adds a label before printing each line.
Bash Scripting
while IFS= read -r line; do
  echo "Line: $line"
done < file.txt
Sample Program

This script reads a file named sample.txt line by line. It prints each line with its number. It also checks if the file exists before reading.

Bash Scripting
#!/bin/bash

# Read file line by line and print each line with line number
filename="sample.txt"

if [[ ! -f "$filename" ]]; then
  echo "File not found: $filename"
  exit 1
fi

count=1
while IFS= read -r line; do
  echo "Line $count: $line"
  ((count++))
done < "$filename"
OutputSuccess
Important Notes

Always quote variables like "$line" to preserve spaces and special characters.

Use IFS= and -r to avoid common pitfalls with spaces and backslashes.

Redirect the file into the loop using done < filename to read from the file.

Summary

Use while IFS= read -r line to read files line by line safely.

Process each line inside the loop for automation or data extraction.

Always check if the file exists before reading to avoid errors.