← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 2 of 13

The read Command and Here-Strings

The read command lets a script grab a line of text and store it in a variable, and a here-string is a quick way to feed it text without typing anything at a keyboard.

Reading a Value Without Real stdin

The read builtin reads a line from its input and stores it in one or more variables. A here-string (<<<) lets you hand it a literal string as if it had been typed, which is perfect for scripts that have no interactive terminal attached.

Note: Always prefer -r unless you specifically want backslash escapes interpreted.

Example: Reading a Value Without Real stdin

bash
#!/bin/bash
read -r name <<< "Ada Lovelace"
echo "Hello, $name"

Reading Multiple Variables at Once

When read is given several variable names, it splits the input on IFS (whitespace by default) and assigns one field per variable. Any leftover words are all stuffed into the last variable.

Example: Reading Multiple Variables at Once

bash
#!/bin/bash
read -r first last <<< "Grace Hopper"
echo "First: $first"
echo "Last: $last"

read -r a b c <<< "one two three four"
echo "c holds the rest: $c"

Reading Into an Array

The -a flag tells read to split the input on IFS and store every field into an indexed array in one shot, which is often cleaner than declaring several named variables.

Example: Reading Into an Array

bash
#!/bin/bash
read -r -a words <<< "bash scripting is fun"
echo "Word count: ${#words[@]}"
echo "Second word: ${words[1]}"

Custom Field Separator with IFS

You can temporarily change IFS just for one read call to split on something other than whitespace, such as a colon, which is handy for parsing lines like /etc/passwd entries.

Note: Setting IFS= right before the command only affects that single command, so it does not leak into the rest of the script.

Example: Custom Field Separator with IFS

bash
#!/bin/bash
IFS=':' read -r user pass uid <<< "root:x:0"
echo "User: $user, UID: $uid"
Common Mistakes
  1. Assuming read always waits for a human to type something; it happily reads from any input source, including a here-string or a file.
  2. Forgetting that read without -r will interpret backslashes as escape characters, silently mangling paths like C:\temp.
  3. Not realizing a here-string automatically appends a trailing newline to the text before feeding it to the command.
Chapter Summary
  • read var <<< "text" feeds text to read as if it were typed, without needing real stdin.
  • read -r disables backslash escaping and should be your default.
  • read a b c <<< "x y z" splits on whitespace (IFS) into multiple variables at once.
  • read -a arr <<< "..." reads whitespace-separated words directly into an array.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.