Reading input and here documents
Read user input and file lines with read -r, split fields with IFS, and feed blocks of text to commands with here documents and here strings.
RedirectionLoops - for, while and untilWord splitting and the order of expansionFunctions, arguments and scope
Reading input and here documents
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `read -r var` reads one line from standard input into `var`. Always pass `-r`, or backslashes in the input are treated as escapes.
- `read` splits the line on `IFS` and assigns words to the names you give it. The last name gets the remainder, and `IFS= read -r` keeps leading and trailing whitespace.
- `read` returns non-zero at end of input, which is what ends a `while read` loop, and a last line with no newline is still captured into the variable.
- A here document, `<<EOF`, feeds literal lines to a command's standard input. Quoting the delimiter, `<<'EOF'`, turns off expansion inside it, and `<<-` strips leading tabs.
- A here string, `<<< "text"`, feeds one string to standard input without a pipe, so the command runs in your shell.
Getting data into a script
Scripts need input from three places: the person running them, files, and text you want to write inside the script itself. Bash gives you read for the first two and here documents for the third. Both come down to the same thing you’ve seen since the streams lesson: standard input is a stream, and these are ways to fill it.
read takes a line
read reads one line from standard input and stores it in a variable. Add -p for a prompt. This script asks two questions:
#!/usr/bin/env bash
read -r -p "Name: " name
read -r -p "Proceed [y/N]? " answer
case ${answer:-n} in
[yY]*) echo "ok, $name" ;;
*) echo "cancelled" ;;
esac
I fed it from a pipe, since I can’t type into a test run:
$ printf 'ada\ny\n' | ./ask.sh
ok, ada
$ printf 'ada\n' | ./ask.sh
cancelled
The second run shows the ${answer:-n} default working at end of input. Note that the prompts never appeared. Bash prints the -p prompt only when input comes from a terminal, so I didn’t see that part run, and I can’t show it. ShellCheck reported nothing on the script.
Always use -r. Without it, read treats a backslash as an escape character, which silently eats data:
$ echo 'back\slash' | { read line; echo "no -r: $line"; }; echo 'back\slash' | { read -r line; echo "with -r: $line"; }
no -r: backslash
with -r: back\slash
Splitting into fields
read splits its line using IFS, the same rule as word splitting, and gives one word to each variable you name. The last variable receives everything left:
$ read -r a b rest <<< "one two three four"; echo "a=$a b=$b rest=$rest"
a=one b=two rest=three four
$ read -r only <<< " padded "; echo "[$only]"; IFS= read -r only <<< " padded "; echo "[$only]"
[padded]
[ padded ]
Plain read trims leading and trailing whitespace, and IFS= read -r doesn’t. Setting IFS in front of the command applies to that command only, which makes CSV parsing neat:
$ IFS=, read -r name team city score < <(sed -n 2p data/people.csv); echo "$name/$team/$city/$score"
ada/infra/london/91
read -a parts stores the words in an array. That worked in my test (3 parts, last z), and arrays get their own lesson.
End of input
read returns non-zero when it hits the end of its input. That’s what ends a while read loop, as in the loops lesson. One subtlety: if the last line has no trailing newline, read returns non-zero, but the text is still in the variable:
$ printf 'no newline at end' | { read -r l; echo "status: $? got: [$l]"; }
status: 1 got: [no newline at end]
A loop written as while read -r l; do ... would skip that last line. The idiom while read -r l || [[ -n $l ]] handles it.
read -t SECONDS sets a timeout, and -s hides what’s typed, for passwords. A timeout shows an important version difference:
$ sleep 3 | { read -t 1 -r v; echo "timeout status: $?"; }
timeout status: 142
Bash 5.3 returned 142, a status above 128 that means “timed out” and is distinguishable from end of input. Bash 3.2 on macOS returned 1, the same as end of input, and rejected a fractional timeout such as -t 0.5 with “invalid timeout specification”. I ran both.
Here documents
Often you want to embed several lines of text in a script, such as a usage message, a config file template, or SQL. A here document supplies those lines as standard input to a command. After <<, you pick a delimiter word, and everything up to a line containing only that word is the input.
cat <<EOF
Report for $user
file: $log
lines: $(wc -l < "$log" | tr -d ' ')
cost: \$5 and a backslash \\
EOF
Report for reader
file: logs/access.log
lines: 200
cost: $5 and a backslash \
With an unquoted delimiter, the body is treated like double quotes: variables, command substitution and a few backslash escapes are expanded. Quote the delimiter, as in <<'EOF', and the body is taken literally. With that form, a line reading Literal: $user $(date) \n stays as typed came out exactly as written.
That is the right choice when the text contains $ signs that must survive, such as a script you’re generating.
<<-EOF strips leading tabs (not spaces) from each line, so you can indent a here document inside an if and keep it tidy. The closing delimiter must be alone on its line, with no trailing space, and with <<- it may be tab-indented. My test printed indented with tabs, tabs stripped and kept the two spaces on the next line.
Here strings
A here string, <<<, sends a single string to standard input:
$ grep -c . <<< $'a\nb\nc'
3
Its main value is with read. Unlike echo "$s" | read x, it doesn’t create a pipeline, so read runs in your shell and the variable survives. The subshell lesson explains why.
About the video
“Heredocs in Bash! Understanding how they work and a few gotchas” is You Suck at Programming episode 69, 6 minutes 52 seconds, from September 2025, by Dave Eddy. The description is only links, and I had no transcript, so I can’t list the gotchas it covers. Its subject is here documents only, so read comes from the text above. It is in English. Anthony Sottile’s three-minute heredoc video is linked as a second view.
Where this fits
You can now take options, questions and embedded text. Next, a way to hold many values at once: arrays and associative arrays.
Check yourself
What goes wrong if you read with `read line` instead of `read -r line` and the input contains `back\slash`?
Without `-r`, `read` treats the backslash as an escape and drops it, so you get `backslash`. With `-r` the backslash is kept.
How do you split a CSV line into fields with `read`?
Set `IFS` for that one command: `IFS=, read -r name team city score <<< "$line"`. The last variable takes any remaining fields.
What is the difference between `<<EOF` and `<<'EOF'`?
With a bare delimiter, `$variables`, `$(commands)` and backslash escapes inside the document are expanded. A quoted delimiter passes the text through exactly as written.
Why use `<<<` instead of `echo "$s" | read x`?
In a pipeline, `read` runs in a subshell, so `x` vanishes when it ends. A here string keeps `read` in the current shell, so the variable survives.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.