Reading User Input with read
A script that always does the same thing is useful, but a script that can ask a question and act on the answer is far more flexible. In Bash, the built-in command read is the main tool for this. It takes one line of text from standard input, splits it into words, and stores the result in one or more variables.
How read Works
read is a shell built-in, so it runs inside the current shell process and can set variables directly. When it runs, it:
- Waits for a line of input from standard input (normally the keyboard).
- Stops reading at the first newline character and discards that newline.
- Splits the line into fields using the characters in the
IFSvariable (by default: space, tab, and newline). - Assigns the fields to the variable names you gave it.
Because read takes its text from standard input, it works the same way whether the text comes from a person typing, from a file redirected into the script, or from another command.
Syntax
read [options] [variable ...]
If you give no variable name, read stores the whole line in a special variable called REPLY. Every option is optional, and the most common ones are listed here.
| Option | Meaning |
|---|---|
-r | Raw mode: treat backslashes as ordinary characters |
-p text | Show text as a prompt (only when input comes from a terminal) |
-s | Silent mode: do not echo the typed characters |
-n N | Return after reading N characters, without waiting for Enter |
-N N | Read exactly N characters, ignoring delimiters |
-t seconds | Give up after the given number of seconds |
-a name | Store the words in an indexed array called name |
-d char | Stop at char instead of a newline |
A Basic Example
The script below asks for a name and then uses it.
#!/usr/bin/env bash
echo "What is your name?"
read name
echo "Hello, $name"
Running it and typing Asha produces:
What is your name?
Asha
Hello, Asha
The echo prints the question, read name pauses the script until Enter is pressed, and the typed text is stored in the variable name. Note that the variable is written without a dollar sign when read assigns it, and with a dollar sign ($name) when the script uses its value later.
To try read without typing, you can feed it text through a here string (<<<), which supplies a fixed string as standard input:
read name <<< "Asha"
echo "Hello, $name"
Hello, Asha
Showing a Prompt with -p
Printing the question with echo puts the cursor on the next line. The -p option prints the prompt on the same line as the input:
#!/usr/bin/env bash
read -p "Enter your city: " city
echo "You live in $city."
Enter your city: Chennai
You live in Chennai.
Bash writes the prompt to standard error, and only when the input is coming from a terminal. If the input is redirected from a file or a pipe, no prompt is shown. That behavior is helpful, because a script run from a scheduler or a pipeline will not fill its output with prompts nobody can answer.
Reading Several Values at Once
When you list more than one variable, read splits the line into words and gives one word to each variable.
read first last <<< "Ada Lovelace"
echo "First: $first"
echo "Last: $last"
First: Ada
Last: Lovelace
Two rules decide what happens when the number of words and the number of variables do not match:
- If there are more words than variables, the last variable receives all the remaining text, spaces included.
- If there are fewer words than variables, the leftover variables are set to an empty string.
read first last <<< "Ada Lovelace King Countess"
echo "[$first] [$last]"
read a b c <<< "one two"
echo "[$a] [$b] [$c]"
[Ada] [Lovelace King Countess]
[one] [two] []
The Default Variable REPLY
When no variable name is given, the line is stored in REPLY, and in this case the line is kept exactly as typed, with its leading and trailing spaces:
read <<< " spaced input "
echo "[$REPLY]"
[ spaced input ]
Whitespace and the IFS Variable
When you name a variable, read removes leading and trailing whitespace from the value, because those characters belong to IFS:
read value <<< " padded "
echo "[$value]"
[padded]
To keep the spaces, set IFS to an empty string for just that one command by placing the assignment before read:
IFS= read value <<< " padded "
echo "[$value]"
[ padded ]
A variable assignment written directly before a command applies only to that command, so the normal value of IFS is untouched afterwards.
IFS also controls how the line is split. To read a colon-separated record, set IFS to a colon:
IFS=: read -r user password uid rest <<< "root:x:0:0:root:/root:/bin/bash"
echo "$user $uid"
echo "$rest"
root 0
0:root:/root:/bin/bash
The fourth variable, rest, received everything after the third colon, which follows the "last variable takes the remainder" rule.
Why You Should Use -r
Without -r, read treats a backslash as an escape character and removes it. This changes the data, which is rarely what you want:
read path <<< 'C:\temp\new'
echo "[$path]"
read -r path <<< 'C:\temp\new'
echo "[$path]"
[C:tempnew]
[C:\temp\new]
The first command lost both backslashes. The second kept the text intact. A backslash at the end of a line without -r would also join that line to the next one. Use read -r unless you specifically want backslash processing.
Reading Passwords with -s
The -s option stops the typed characters from appearing on the screen. It is meant for secrets such as passwords:
#!/usr/bin/env bash
read -r -s -p "Password: " password
echo
echo "The password has ${#password} characters."
Password:
The password has 6 characters.
Because the user's Enter key is also hidden, the extra echo moves the cursor to a new line. The expression ${#password} gives the length of the value, and the script reports only the length, never the password itself.
Reading a Fixed Number of Characters
The -n option returns as soon as the given number of characters has been typed, without waiting for Enter. It suits single-key answers:
read -r -n 1 -p "Press y or n: " key
echo
echo "You pressed: $key"
Press y or n: y
You pressed: y
-N works like -n, except that it does not treat a newline as the end of input; it reads exactly that many characters, and it also disables IFS splitting.
printf 'abcdef' | { read -r -N 3 chunk; echo "[$chunk]"; }
[abc]
Using a Timeout
With -t, read gives up if nothing arrives in time. This prevents a script from waiting forever for an answer:
if read -r -t 5 -p "Enter a name within 5 seconds: " name; then
echo "Hello, $name"
else
echo
echo "Too slow."
fi
If the user types a name in time, the first branch runs. If five seconds pass, read returns a status greater than 128 (142 in a test with Bash 5.2), and the else branch runs. A timeout does not assign anything to the variable, so it stays empty.
Reading Words into an Array
The -a option stores each word in an indexed array, which is handy when the number of words is not known in advance:
read -r -a colors <<< "red green blue"
echo "Count: ${#colors[@]}"
echo "Second: ${colors[1]}"
Count: 3
Second: green
Array indexes start at 0, so ${colors[1]} is the second word.
Checking the Exit Status of read
read reports whether it managed to read a complete line:
- Status 0: a line was read and ended with a newline.
- Status 1: end of input was reached before a newline arrived.
- Status above 128: the
-ttimeout expired.
At end of input, read still stores any partial text it collected:
printf 'partial' | { read line; echo "status=$? line=[$line]"; }
status=1 line=[partial]
Scripts that read from files rely on this status to know when to stop. A later lesson on reading files line by line builds on it.
Why a Pipe into read Seems to Lose the Value
A common surprise appears when read is placed at the end of a pipe:
echo hello | read x
echo "x=[$x]"
x=[]
Each part of a pipeline normally runs in its own subshell, a separate child copy of the shell. The variable x was set inside that child, which disappears when the pipeline ends, so the parent shell never sees it. There are two simple ways around this, and both are shown here:
read x < <(echo hello)
echo "x=[$x]"
read x <<< "$(echo hello)"
echo "x=[$x]"
x=[hello]
x=[hello]
The first form uses process substitution (<(...)), which treats a command's output as a file. The second captures the output with command substitution and feeds it in as a here string. Neither one creates a subshell for read itself, so the variable survives.
Asking a Yes or No Question
Real scripts usually combine read with a loop and a case statement so that bad answers are rejected. This example also offers a default answer when the user just presses Enter.
#!/usr/bin/env bash
while true; do
read -r -p "Continue? [y/N] " answer
answer=${answer:-N}
case ${answer,,} in
y|yes) echo "Continuing"; break ;;
n|no) echo "Stopping"; break ;;
*) echo "Please answer y or n." ;;
esac
done
Feeding it the answers maybe and Y shows the loop at work:
Continue? [y/N] maybe
Please answer y or n.
Continue? [y/N] Y
Continuing
Pressing Enter on its own gives an empty answer:
Continue? [y/N]
Stopping
The pieces work together like this:
${answer:-N}replaces an empty value withN, which is the default shown in capital letters in the prompt.${answer,,}converts the answer to lower case (a Bash 4 feature), soY,y, andYESare all treated alike.- The
casestatement matches the answer against patterns; the*)pattern catches everything else. breakleaves thewhile trueloop once a valid answer is found.
Reading from a File Descriptor
By default read uses standard input. The -u option reads from another file descriptor instead, which is useful in loops where standard input is already busy. Descriptors, redirection, and loops that read files are covered in later lessons of this tutorial, so for now it is enough to know that the option exists.