---
title: "How do I read a file line by line in Bash?"
description: "Read a file one line at a time with while IFS= read -r, keep leading spaces and backslashes intact, handle a missing final newline, and avoid subshell surprises."
url: https://www.danny.engineering/answer/bash/how-do-i-read-a-file-line-by-line-in-bash
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T17:23:00.000Z
tags: ["Bash"]
---

# How do I read a file line by line in Bash?

## The short answer


Use a `while` loop with `read`, redirect the file into the loop, and set `IFS=` and `-r` so each line arrives exactly as written.


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


## Why it happens


The obvious approach, `for line in $(cat file)`, does not loop over lines at all. The shell splits the output of `cat` on every space, tab and newline, and then expands any `*` or `?` as file name patterns. A line like `hello world` becomes two iterations, and a line containing `*` turns into a list of files in the current directory.


`read` is the tool designed for this. It reads one line from standard input into a variable. By default, though, it changes the line in two ways:

- It trims leading and trailing whitespace, because those characters are in `IFS`, the input field separator. Setting `IFS=` for just the `read` command turns that off.
- It treats a backslash as an escape character, so `C:\temp` loses its backslash and a backslash at the end of a line joins it to the next one. The `-r` flag turns that off.

The `|| [[ -n "$line" ]]` part handles files whose last line has no trailing newline. `read` returns a failure status when it hits the end of the file, even if it did read some text first, so without this check the last line is silently skipped.


## How to fix it


### The standard loop


```bash
file="hosts.txt"

while IFS= read -r line || [[ -n "$line" ]]; do
  [[ -z "$line" || "$line" == \#* ]] && continue   # skip blank lines and comments
  echo "Pinging $line"
done < "$file"
```


The redirection goes after `done`, so it applies to the whole loop and the file is opened once.


### Split each line into fields


Give `read` several variable names and set `IFS` to the separator. The last variable gets the rest of the line.


```bash
while IFS=, read -r name email role; do
  echo "$name has role $role"
done < users.csv
```


This is fine for simple comma-separated data. It does not understand quoted fields containing commas, so use a real CSV tool for anything more complex.


### Read the output of a command


Piping into the loop works, but each part of a pipeline runs in a subshell. Variables set inside the loop are lost when it ends:


```bash
count=0
grep ERROR app.log | while IFS= read -r line; do
  (( count++ ))
done
echo "$count"   # prints 0
```


Use process substitution instead, which keeps the loop in the current shell:


```bash
count=0
while IFS= read -r line; do
  (( count++ ))
done < <(grep ERROR app.log)
echo "$count"   # prints the real count
```


### Load all lines into an array


In Bash 4 and later, `mapfile` (also called `readarray`) reads every line into an array in one go. `-t` removes the trailing newline from each element.


```bash
mapfile -t lines < input.txt
echo "Read ${#lines[@]} lines"
for line in "${lines[@]}"; do
  printf '%s\n' "$line"
done
```


The `/bin/bash` that ships with macOS is version 3.2, which does not have `mapfile`. Install a newer Bash with Homebrew, or stick with the `while read` loop if the script must run there.


### Commands inside the loop that read input


Anything inside the loop that reads standard input, such as `ssh`, `ffmpeg` or another `read`, will swallow the rest of the file and the loop stops early. Read the file on a different file descriptor:


```bash
while IFS= read -r -u 3 host; do
  ssh "$host" uptime
done 3< hosts.txt
```


For `ssh` specifically, `ssh -n` also works.


## Common pitfalls

- Using `for line in $(cat file)`. It splits on spaces and expands globs.
- Forgetting `-r`, so backslashes disappear.
- Forgetting `IFS=`, so indentation is stripped from every line.
- Losing the last line of a file with no trailing newline.
- Piping into `while` and expecting variables to survive the loop.
- Reading Windows files with CRLF line endings. Each line keeps a trailing carriage return, which breaks comparisons. Strip it with `line=${line%$'\r'}` inside the loop, or convert the file with `dos2unix`.
- Reaching for a Bash loop to process large files. Tools like `awk`, `grep` and `sed` are far faster for line-by-line work on big inputs.

## Related reading

- [GNU Bash manual: Bash builtins, read and mapfile](https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html)
