Reading User Input with read

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 31 of 205

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:

  1. Waits for a line of input from standard input (normally the keyboard).
  2. Stops reading at the first newline character and discards that newline.
  3. Splits the line into fields using the characters in the IFS variable (by default: space, tab, and newline).
  4. 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.

OptionMeaning
-rRaw mode: treat backslashes as ordinary characters
-p textShow text as a prompt (only when input comes from a terminal)
-sSilent mode: do not echo the typed characters
-n NReturn after reading N characters, without waiting for Enter
-N NRead exactly N characters, ignoring delimiters
-t secondsGive up after the given number of seconds
-a nameStore the words in an indexed array called name
-d charStop 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 -t timeout 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 with N, which is the default shown in capital letters in the prompt.
  • ${answer,,} converts the answer to lower case (a Bash 4 feature), so Y, y, and YES are all treated alike.
  • The case statement matches the answer against patterns; the *) pattern catches everything else.
  • break leaves the while true loop 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Reading User Input with read and get answers drawn from it.

Signed-in readers only.