Read input with read -r
read -r name reads one newline-delimited record from stdin into a shell variable, without interpreting backslashes as escape characters. The delimiter is removed. These examples read text, not arbitrary binary data: ordinary Bash read skips NUL bytes, and Bash variables cannot store a NUL byte. For a delimiter other than newline, read -d is a Bash option; an empty delimiter argument (-d '') reads up to NUL. Default IFS processing can trim leading and trailing spaces or split input among named variables; IFS= read -r name preserves surrounding whitespace and literal backslashes. With no variable name, Bash uses REPLY. read -p displays a prompt only when input is from a terminal. To run deterministic examples without typing, this chapter uses files created by printf. The examples use && to print only after setup and each read succeed. A failed read can still retain partial data; the next lesson handles EOF.
Practical examples
Run each example separately in Bash 5.2 in a fresh empty practice directory, using default shell options and C locale. Output is shown separately; do not enter it as code.
Preserve backslashes
printf '%s\n' 'docs\notes' > input.txt && IFS= read -r path < input.txt && printf '[%s]\n' "$path"Expected stdout:
[docs\notes]Expected stderr:
No output
Overall example exit status: 0
The backslash remains an ordinary character.
Preserve spaces
printf '%s\n' ' report ' > input.txt && read -r a < input.txt && IFS= read -r b < input.txt && printf '[%s]\n' "$a" "$b"Expected stdout:
[report][ report ]Expected stderr:
No output
Overall example exit status: 0
Empty IFS prevents trimming in this example.
Split a controlled record
printf '%s\n' 'blue large' > input.txt && read -r color size < input.txt && printf '%s / %s\n' "$color" "$size"Expected stdout:
blue / largeExpected stderr:
No output
Overall example exit status: 0
Default IFS separates the two fields. This is not a general CSV parser.
Common mistakes
Do not assume read name preserves a path with backslashes. Do not assume read -r alone preserves whitespace. Use IFS= read -r for a literal line and quote the result when using it.
Practice
Create a one-line file containing two leading spaces, a literal backslash, and a trailing space. Read it with IFS= read -r and print brackets around the value.
Next: EOF and unterminated lines