Reading Input with read and IFS

Reading Input with read and IFS in Bash: Picture the deposit window at an old-fashioned bank branch.

The Analogy: The Bank Teller's Deposit Window

Picture the deposit window at an old-fashioned bank branch. Customers slide paper deposit slips across the counter one after another, and the teller works through them in order: pick up the next slip, read it, act on it, reach for the next. The teller never grabs the whole stack at once and never skips ahead; the slips arrive as a stream and are handled strictly one at a time. This one-at-a-time rhythm -- take the next record, process it, loop back for another -- is exactly how the read builtin drives a loop over lines of input.

Each deposit slip is not a single blob of ink; it is divided into ruled boxes -- account number, amount, date -- and the printed vertical rules tell the teller where one field ends and the next begins. When the teller copies the slip into the day-book, they read across those rules, dropping each box into its own column. In the shell, that set of dividing rules is the Internal Field Separator, IFS. By default the rules are drawn at every run of spaces and tabs, so a line splits into whitespace-separated words; set IFS=, and you have re-ruled the form for a comma-separated slip instead.

The teller also has a rule about how literally to copy. Normally they transcribe every mark on the slip exactly as written, even an odd stray back-slash a customer scrawled, because the ink is data, not an instruction to the teller. That faithful, take-it-literally mode is read -r. Without it, read treats a back-slash as a private signal -- an escape or a "continued on the next line" mark -- and quietly rewrites what the customer actually wrote. A careful teller almost always copies literally, which is why almost every correct loop uses read -r.

The window has one failure that stings at closing time. If the teller hands the stack through a pneumatic tube to a back-office clerk to tally, the running total the back-office builds lives in that back room; when the tube closes, the teller's own drawer never learns it. Piping a stream into while read does the same thing: the loop runs in a subshell, and any total it accumulates is gone the moment the loop ends. And a slip whose bottom edge was torn off before the completion stamp -- a final line with no newline -- can be set aside unread, so the very last record silently never reaches the day-book. Both traps are quiet: nothing errors, the numbers are just wrong.


Syntax or Core Structure

read pulls one line from its input, splits that line into fields using the characters in IFS, and assigns the fields to the variable names you give it. Put it in a while loop and it walks a whole stream, line by line, until the input runs dry:

echo 'alice 42 london' | while read -r name age city; do
  echo "name=$name age=$age city=$city"
done

Output:

name=alice age=42 city=london

The default IFS splits on whitespace, so the single line became three fields. Two details make this the workhorse pattern. First, read returns a success status for every line it reads and a failure status at end of input, which is exactly the condition a while loop wants. Second, the number of variables does not have to match the number of fields: give it fewer names than fields and the last name soaks up everything that is left.

echo 'alice 42 london UK' | while read -r name rest; do
  echo "name=$name rest=$rest"
done

Output:

name=alice rest=42 london UK

Here name takes the first word and rest receives the entire remainder, spaces and all. This "last variable catches the rest" behaviour is deliberate and useful: it lets you peel off a leading key and keep the unparsed tail in one piece for later.

Technical Depth: Fields, Raw Mode and Where the Loop Runs

Re-ruling the form with IFS

Setting IFS in front of read changes the dividing rules for that read alone, which is how you parse structured records. A comma-separated visit log reads cleanly by re-ruling the form to a comma:

while IFS=, read -r user path code; do
  echo "$user visited $path (status $code)"
done < visits.csv

Output:

alice visited /home (status 200)
bob visited /login (status 200)
alice visited /home (status 200)
carol visited /api (status 500)
bob visited /home (status 200)
alice visited /api (status 500)

Writing IFS=, as a prefix on the same line scopes the change to that one command: the loop reads comma-separated fields, but IFS returns to normal everywhere else. That is far safer than assigning IFS on its own line, which would quietly change word-splitting for the rest of the script.

SettingField rule
defaultsplit on runs of spaces, tabs and newlines
IFS=,split on each single comma
IFS=:split on each single colon, as in /etc/passwd
IFS= (empty)no splitting; the whole line goes into one variable

Colon-separated records such as /etc/passwd read the same way, and when you only want a couple of the fields you can name the ones you care about and use the throwaway variable _ for the rest:

echo 'root:x:0:0:root:/root:/bin/bash' | while IFS=: read -r user _ uid _ _ _ shell; do
  echo "$user (uid $uid) -> $shell"
done

Output:

root (uid 0) -> /bin/bash

Naming seven variables lines each one up with a field by position, and _ is a conventional "I do not need this" placeholder -- it is a real variable, but the name signals to a reader that its value is deliberately ignored. This positional read is why read is the natural tool for fixed-layout records.

Copying literally: why -r matters

Without -r, read treats a back-slash as an escape character and removes it, mangling any real data that legitimately contains back-slashes -- Windows paths being the classic casualty:

line='C:\Users\Harsh'
read -r p <<< "$line"; echo "with -r: $p"
read q    <<< "$line"; echo "no -r : $q"

Output:

with -r: C:\Users\Harsh
no -r : C:UsersHarsh

With -r the path survives intact; without it, every back-slash is eaten and the path collapses into nonsense. There is almost no situation where the escape-processing of bare read is what you want, so treat read -r as the default and reach for plain read only when you deliberately want back-slash line continuation.

Keeping the blanks: IFS= and read

By default read also strips leading and trailing whitespace, because spaces are field separators and empty edge-fields are discarded. When you must preserve a line exactly -- indentation and all -- clear IFS for that read:

printf '   indented\n' | while read -r line; do echo "[$line]"; done
printf '   indented\n' | while IFS= read -r line; do echo "[$line]"; done

Output:

[indented]
[   indented]

The first loop trims the three leading spaces; the second, with IFS= emptying the separator set, keeps them. The idiom while IFS= read -r line -- empty IFS, raw mode -- is the canonical way to read a file one whole, untouched line at a time, and it is worth memorising as a single unit.

Reading several words into an array

With -a, read splits the line and drops the pieces into an array instead of named variables, which is handy when you do not know how many fields there will be:

read -r -a parts <<< 'a b c'
echo "${parts[0]} / ${parts[2]} / count=${#parts[@]}"

Output:

a / c / count=3

The three words land in parts[0], parts[1] and parts[2], and ${#parts[@]} reports the count. A here-string, written <<<, feeds a single string to read as its input without any pipe, which -- as the next section shows -- also sidesteps a notorious trap.

Where the loop runs: pipe versus redirect

Every command on the right of a | runs in a subshell, a separate process whose variable changes cannot flow back to the parent. Feed a loop with a pipe and any total it builds evaporates when the loop ends:

count=0
cat visits.csv | while read -r _; do count=$((count+1)); done
echo "after pipe:     count=$count"

count=0
while read -r _; do count=$((count+1)); done < visits.csv
echo "after redirect: count=$count"

Output:

after pipe:     count=0
after redirect: count=6

Both loops count the same six lines, but the piped one throws its answer away with the subshell, leaving count at its original 0. Redirecting the file into the loop with < file keeps the loop in the current shell, so count survives. Prefer done < file over cat file | while for both correctness and one fewer process.

Real World Example: A Weekly Payroll Reader

A payroll clerk keeps hours in a plain name,rate,hours file and needs a weekly pay run: multiply rate by hours for each person, print a padded row, and total the column at the end. This payroll.sh reads the file one record at a time, splitting on the comma, and keeps a running total in the current shell by feeding the file with a redirect rather than a pipe.

#!/usr/bin/env bash
# payroll.sh -- weekly pay from a name,rate,hours file
set -euo pipefail

FILE="${1:-hours.csv}"
total=0

while IFS=, read -r name rate hours; do
  pay=$(( rate * hours ))
  printf '%-8s %5d\n' "$name" "$pay"
  total=$(( total + pay ))
done < "$FILE"

printf '%-8s %5d\n' "TOTAL" "$total"

Given a file of alice,20,40, bob,15,35 and carol,25,38, it prints:

Output:

alice      800
bob        525
carol      950
TOTAL     2275

The engine is a single while IFS=, read -r name rate hours line. IFS=, re-rules each record into three comma-separated fields, -r copies them literally, and the three names catch the three columns. Because the file arrives through done < "$FILE" -- a redirect, not a pipe -- the loop runs in the current shell, so total accumulates across iterations and is still 2275 when the final printf reads it. Integer arithmetic with $(( rate * hours )) needs no external tool, and printf with %-8s %5d lines the columns up.

The redirect also keeps the pattern composable. Swap the field names to read a different layout, change IFS=, to IFS=: for a colon file, or point FILE at any path through the first argument. Every stage is standard bash, there are no temporary files, and the script streams: it never holds more than one line in memory, so a payroll of ten people and one of ten thousand cost the same memory.

The script has a real flaw that hides in the last line of the input. The loop condition is read -r ..., and read returns a failure status when it hits end of input -- even when it did manage to populate the variables from a final line that had no trailing newline. So an hours.csv whose last line is carol,25,38 with no newline after it drops carol entirely: the run prints only alice and bob and a TOTAL of 1325, understated by 950, with no error at all. The fix is to keep looping while the read succeeds OR the last variable is non-empty -- while IFS=, read -r name rate hours || [ -n "$name" ] -- which processes that unterminated final record before stopping. Any script that reads files it did not create should carry that guard, because "someone's editor did not add a trailing newline" is a routine, silent event.


Common Mistakes

  1. Forgetting -r and eating back-slashes. Bare read treats a back-slash as an escape, so paths, regexes and Windows filenames get silently corrupted. Use read -r unless you have a specific reason not to.
  1. Piping a file into the loop when you need a result afterwards. cat file | while read ...; do total=...; done runs the loop in a subshell, so total is back to its old value once the loop ends. Redirect with done < file instead.
  1. Losing the last line of a file with no trailing newline. read returns failure on that final unterminated line, so the loop skips it. Guard the condition with || [ -n "$line" ].
  1. Setting IFS on its own line instead of per-command. A bare IFS=, statement changes splitting for the whole rest of the script. Prefix it on the read -- IFS=, read -r ... -- to scope it to that one command.
  1. Letting read trim whitespace you needed. Default read strips leading and trailing blanks. To keep a line verbatim, clear the separator: while IFS= read -r line.
  1. Using for line in $(cat file) to read lines. That splits on every space, not on newlines, so a line containing spaces becomes several iterations. Use a while read loop for lines.
  1. Assuming a variable-to-field mismatch is an error. Extra names simply come back empty, and too few names make the last one absorb the rest. Neither is an error, so a mismatch fails silently rather than loudly.
  1. Reading and writing the same file in one command. while read ... < file > file truncates the file before the loop reads it. Write to a temporary file and move it into place afterwards.
  1. Forgetting to quote $line when you use it. An unquoted echo $line re-splits and glob-expands the value you just carefully read. Always write "$line".

Best Practices

  • Default to while IFS= read -r line. Empty IFS plus raw mode reads each line exactly as written; make it your reflex for line-by-line file processing.
  • Feed files with a redirect, not a pipe. done < file keeps the loop in the current shell so counters and totals survive, and it spares you a cat process.
  • Scope IFS to the single read. Prefix IFS=, on the read line so the change cannot leak into the rest of the script's word-splitting.
  • Add the || [ -n "$var" ] guard when a missing final newline is possible. It processes an unterminated last record instead of dropping it silently.
  • Quote every expansion of what you read. Writing "$line" and "$name" stops the shell re-splitting and glob-expanding values that came straight from data.
  • Use read -a when the field count is unknown. An array scales to any number of columns without inventing names you will never use.
  • Prefer printf over echo for formatted rows. printf gives you column widths and predictable output; echo cannot pad or align.
  • Validate fields before trusting them. A record read from a file may be short, blank or malformed; check that the fields you require are present before doing arithmetic on them.

Practice Exercises

  1. Read a passwd file. Write a loop that reads /etc/passwd with IFS=: and prints, for each line, the username (field 1) and the login shell (field 7) as user -> shell. Confirm it handles every line of the file.
  1. Recover the last line. Take a file data.txt whose last line has no trailing newline and show, with a line-counting loop, that the naive version undercounts by one. Then add the || [ -n "$line" ] guard and show the count is now correct.
  1. Expose the subshell trap. Build a running sum of a numeric column two ways -- once with cat file | while read and once with while read ... done < file -- and explain why only the second prints the right total.
  1. Handle unknown widths. Write a loop using read -r -a fields that prints the first and last element of each whitespace-separated line, plus the number of fields, without hard-coding how many columns each line has.