Reading Files Line by Line

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 114 of 205

Many scripts process a file one line at a time: a list of servers to check, a configuration file to parse, a log to scan, a list of users to create. Bash does this with a while loop around the read builtin, with the file redirected into the loop:

while IFS= read -r line; do
    printf '[%s]\n' "$line"
done < notes.txt

Each pass of the loop reads one line into the variable line. When read reaches the end of the file it returns a non-zero status, and the loop stops. This lesson explains each part of that line, shows why the obvious alternatives go wrong, and covers the situations that need extra care.

The Sample File

notes.txt contains five lines, including leading spaces, a backslash and an empty line:

printf '%s\n' 'first line' '  indented line' 'back\slash' '' 'last line' > notes.txt

The loop above prints every line exactly as stored. The brackets show where each value starts and ends:

[first line]
[  indented line]
[back\slash]
[]
[last line]

Understanding Each Part

while ... done < file

The redirection < notes.txt after done connects the file to the standard input of the whole loop (lesson 58). Every read inside the loop continues from where the previous one stopped, so the loop walks through the file from top to bottom. The file is opened once, before the first pass.

read returns status 0 when it reads a line and status 1 at the end of the input. while runs its body as long as the condition command succeeds (lesson 80), so the loop ends naturally after the last line.

read -r

Without -r, read treats a backslash as an escape character: it removes the backslash and joins a line that ends in 0 with the next one. -r` (raw) keeps backslashes as ordinary characters. There is almost never a reason to leave it out.

IFS=

read splits its input using the characters in IFS and, with only one variable name, removes leading and trailing whitespace from the line. Writing IFS= directly before read sets IFS to an empty value for that one command only, so nothing is trimmed and the line arrives unchanged.

The difference is easy to see by dropping both IFS= and -r:

while read line; do
    printf '[%s]\n' "$line"
done < notes.txt
[first line]
[indented line]
[backslash]
[]
[last line]

The indentation and the backslash are gone. For data where whitespace and backslashes matter, such as file paths, source code or configuration values, that is silent corruption.

Quoting the Variable

Inside the loop, "$line" must be quoted wherever it is used. An unquoted $line is split into words and its wildcards are expanded (lesson 55), which undoes the care taken by IFS= read -r.

The REPLY Variable

When read is given no variable name, it stores the line in REPLY. In this form Bash does not trim whitespace, even without IFS=:

while read -r; do printf '[%s]\n' "$REPLY"; done < notes.txt

The first two lines of output are [first line] and [ indented line]. Naming the variable makes the code easier to read, so the rest of this lesson uses IFS= read -r line.

Why for line in $(cat file) Is Wrong

A for loop over command output looks simpler but does not loop over lines:

for line in $(cat notes.txt); do
    printf '[%s]\n' "$line"
done
[first]
[line]
[indented]
[line]
[back\slash]
[last]
[line]

The unquoted $(cat notes.txt) is split at every space, tab and newline, so the loop sees words, not lines. Leading spaces and the empty line disappear, and any * or ? in the file would be expanded as a filename pattern. It also reads the entire file into memory before the loop starts. Lesson 83 covers this trap in detail.

Counting and Numbering Lines

Variables set inside a loop that reads from < file keep their values after the loop, because the loop runs in the current shell:

n=0
while IFS= read -r line; do
    n=$((n + 1))
    printf '%2d: %s\n' "$n" "$line"
done < notes.txt
echo "n=$n"
 1: first line
 2:   indented line
 3: back\slash
 4: 
 5: last line
n=5

Feeding the same loop through a pipe gives a different result:

n=0
cat notes.txt | while IFS= read -r line; do n=$((n + 1)); done
echo "n=$n"
n=0

Each part of a pipeline runs in its own subshell (lesson 61), so the counter changes only in the subshell and is lost when the loop ends. Redirect the file into the loop instead of piping cat into it.

The Last Line Without a Newline

A text file normally ends with a newline character. Files written by some editors or generated by programs sometimes do not, and read then returns status 1 for the last line even though it did read text into the variable. The loop stops before running the body for that line:

printf 'alpha\nbeta\ngamma' > nonl.txt

while IFS= read -r line; do
    echo "[$line]"
done < nonl.txt
[alpha]
[beta]

gamma was read but never processed. wc -l nonl.txt reports 2 for the same reason: it counts newline characters, not lines.

Adding || [[ -n $line ]] to the condition runs the body one more time when the final read returned text:

while IFS= read -r line || [[ -n $line ]]; do
    echo "[$line]"
done < nonl.txt
[alpha]
[beta]
[gamma]

At the true end of the file, read fails and leaves line empty, so the extra test is false and the loop ends. This form is safe to use for every file, whether or not it ends with a newline.

Skipping Comments and Blank Lines

Configuration files usually contain comments and empty lines that the script must ignore. A test at the top of the loop and continue (lesson 84) skip them:

# app.conf
# app settings
host = example.org

port=8080
  # indented comment
name = My App   
while IFS= read -r line; do
    [[ $line =~ ^[[:space:]]*(#|$) ]] && continue

    key=${line%%=*}
    value=${line#*=}
    key=${key//[[:space:]]/}
    value="${value#"${value%%[![:space:]]*}"}"
    value="${value%"${value##*[![:space:]]}"}"

    printf '%s -> [%s]\n' "$key" "$value"
done < app.conf
host -> [example.org]
port -> [8080]
name -> [My App]

How it works:

  • The regular expression matches a line that, after optional whitespace, starts with # or ends. Those lines are skipped.
  • ${line%%=*} keeps everything before the first =, and ${line#*=} everything after it (lesson 54).
  • ${key//[[:space:]]/} removes all whitespace from the key.
  • The two longer expansions trim leading and trailing whitespace from the value while keeping the space inside My App. The inner expansion finds the run of whitespace at the edge, and the outer one removes exactly that run. The trailing spaces after My App in the file were removed.

The file is read as data and never executed, which is safer than source app.conf for files that other people can edit (lesson 95).

Splitting Each Line into Fields

read can split a line into several variables. Setting IFS to a different character for the read command chooses the separator. /etc/passwd-style data uses colons:

printf 'root:x:0:0:root:/root:/bin/bash\nana:x:1000:1000:Ana Lima:/home/ana:/bin/bash\n' > users.txt

while IFS=: read -r user _ uid _ gecos home shell; do
    printf '%-5s uid=%-5s %s (%s)\n' "$user" "$uid" "$home" "$gecos"
done < users.txt
root  uid=0     /root (root)
ana   uid=1000  /home/ana (Ana Lima)
  • Each field goes into the next variable name in order.
  • _ is a conventional name for fields that are not needed.
  • The last variable receives the rest of the line if there are more fields than names.
  • The space in Ana Lima is kept, because only : separates fields here.

With the default IFS, fields are separated by runs of spaces or tabs, and leading whitespace is ignored, which suits column-aligned output:

printf '  web01   10.0.0.5   up\nweb02 10.0.0.6 down\n' |
    while read -r host ip state; do echo "<$host><$ip><$state>"; done
<web01><10.0.0.5><up>
<web02><10.0.0.6><down>

Lesson 110 applies the same technique to comma-separated data and covers its limits.

Reading the Output of a Command

To loop over the lines a command prints while keeping variables after the loop, use process substitution (lesson 151) instead of a pipe:

while IFS= read -r f; do
    echo "file: $f"
done < <(printf '%s\n' b.txt a.txt | sort)
file: a.txt
file: b.txt

<(...) runs the command and presents its output as a file name; the first < redirects that "file" into the loop. Note the space between the two < characters.

When a Command Inside the Loop Reads Standard Input

The redirection after done gives the file to every command inside the loop, not just to read. A command in the body that reads standard input consumes lines meant for the loop. head -n 1 shows this:

printf 'one\ntwo\nthree\n' > list.txt

while IFS= read -r item; do
    echo "item: $item"
    head -n 1 > /dev/null
done < list.txt
item: one
item: three

head swallowed two. Real scripts hit this with ssh, ffmpeg, mysql and interactive tools, and the symptom is a loop that processes only the first line or skips lines at random.

There are three fixes. The first gives the inner command its own empty input:

head -n 1 < /dev/null > /dev/null

(ssh -n does the same thing for ssh.) The second reads the file on a different file descriptor, so standard input stays untouched:

while IFS= read -r item <&3; do
    echo "item: $item"
    head -n 1 > /dev/null
done 3< list.txt

3< list.txt opens the file on descriptor 3 for the loop, and <&3 makes read take its input from there. The third uses read -u 3, a Bash shortcut for the same thing:

while IFS= read -r -u 3 item; do
    echo "item: $item"
done 3< list.txt

With descriptor 3, all three items were printed. Inside the loop, head read the script's own standard input instead; in a script run from a terminal, that is the keyboard.

Reading Two Files in Parallel

Separate descriptors also let a loop read from two files at once, one line from each per pass:

printf 'Ana\nBo\nCy\n' > names.txt
printf '31\n27\n45\n' > ages.txt

while IFS= read -r name <&3 && IFS= read -r age <&4; do
    echo "$name is $age"
done 3< names.txt 4< ages.txt
Ana is 31
Bo is 27
Cy is 45

The loop stops as soon as either file runs out. For simple side-by-side joining, paste names.txt ages.txt does the same without a loop.

Reading All Lines into an Array

When the script needs random access to the lines, or must go through them more than once, mapfile (also called readarray, Bash 4.0 or later) reads the whole file into an indexed array (lesson 97):

mapfile -t lines < notes.txt
echo "${#lines[@]}"
printf '[%s]\n' "${lines[1]}" "${lines[3]}"
5
[  indented line]
[]
  • -t removes the newline from the end of each element.
  • Whitespace, backslashes and empty lines are kept.
  • A final line without a newline is included: mapfile -t l2 < nonl.txt gives three elements, the last being gamma.

-s N skips the first N lines and -n N reads at most N lines:

readarray -t -s 1 -n 2 part < notes.txt
printf '[%s]\n' "${part[@]}"
[  indented line]
[back\slash]

mapfile holds the entire file in memory, so a while read loop remains the better choice for very large files. Dash and other POSIX shells do not have it (dash: 1: mapfile: not found).

Reading One Specific Line

A loop is unnecessary to get a single line by number. Each of these prints one line of notes.txt:

sed -n '3p' notes.txt
awk 'NR == 5' notes.txt
head -n 2 notes.txt | tail -n 1
back\slash
last line
  indented line

To read a whole small file into one variable, content=$(<notes.txt) is a Bash shortcut for $(cat notes.txt) that reads the file without running the cat program. Like every command substitution, it removes trailing newlines.

Files with Windows Line Endings

A file saved on Windows ends each line with a carriage return followed by a newline. read stops at the newline, so the carriage return stays at the end of the value, invisible but present:

printf 'one\r\ntwo\r\n' > win.txt

while IFS= read -r line; do
    [[ $line == one ]] && echo match || printf '%q\n' "$line"
done < win.txt
$'one\r'
$'two\r'

printf '%q' reveals the \r, and the comparison with one fails. Removing it at the top of the loop fixes every later use:

while IFS= read -r line; do
    line=${line%$'\r'}
    [[ $line == one ]] && echo "match: $line"
done < win.txt
match: one

Converting the file once with tr -d '\r' or dos2unix before processing is an alternative (lesson 110 shows the same fixes for CSV data).

Stopping Early

break leaves the loop as soon as the wanted line is found, without reading the rest of the file:

while IFS= read -r line; do
    if [[ $line == back* ]]; then
        echo "found: $line"
        break
    fi
done < notes.txt
found: back\slash

Empty and Missing Files

An empty file makes the first read fail, so the loop body never runs and a counter stays at 0. A missing file is different: the redirection fails before the loop starts, Bash prints an error, the loop is skipped, and its status is 1:

while IFS= read -r l; do :; done < missing.txt
echo "status $?"
bash: missing.txt: No such file or directory
status 1

The script continues after the error unless set -e is active. Checking [[ -r $file ]] first allows a clearer message (lesson 72).

Speed: When to Use awk Instead

A while read loop runs Bash commands for every line, which is slow compared with tools written for text processing. Summing 20,000 numbers took about 0.08 seconds with a while read loop and about 0.003 seconds with awk on the test system:

c=0
while IFS= read -r l; do c=$((c + l)); done < big.txt
echo "$c"

awk '{ c += $1 } END { print c }' big.txt

Both printed 200010000. Calling an external program inside the loop, such as $(echo "$line" | cut -d, -f2), makes the difference much larger, because a new process starts for every line. Use while read when each line needs shell work such as running commands, moving files or calling functions; use awk, sed or grep (lessons 106-109) for pure text transformation of large files.

Portability

while IFS= read -r line; do ...; done < file works the same way in Dash and every POSIX shell. [[ ]] in the last-line fix, read -u, read -d, $'\r', $(<file) and mapfile are Bash features; in a POSIX script, use [ -n "$line" ], <&3 and tr -d '\r' instead.

The examples were run with Bash 5.2.21, GNU coreutils 9.4, mawk 1.3.4 and Dash. Timings depend on the machine. Error messages are shown in their interactive form.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Reading Files Line by Line and get answers drawn from it.

Signed-in readers only.