Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

In Bash, use the read builtin to obtain a line typed by a user:

#!/usr/bin/env bash

IFS= read -r -p "Enter your name: " name
printf 'Hello, %s!n' "$name"

read normally consumes standard input, which may be the keyboard, a pipe, or a redirected file. The recommended general-purpose form, IFS= read -r, preserves leading and trailing whitespace and treats backslashes literally.

The basic read command

Create a file named hello.sh:

#!/usr/bin/env bash

read -r -p "Enter your name: " name
printf 'Hello, %s!n' "$name"

Make it executable and run it:

chmod +x hello.sh
./hello.sh

A typical interaction is:

Enter your name: Ada Lovelace
Hello, Ada Lovelace!

The variable is assigned without a dollar sign: name, not $name. The dollar sign is used when expanding the value later. Always quote an expansion such as "$name" when it represents one value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

printf is preferred to echo when predictable formatting matters, especially for input containing backslashes or values beginning with a hyphen.

#1 Best Overall
Sale
Redragon Mechanical Gaming Keyboard Wired, 11 Programmable Backlit Modes, Hot-Swappable Red Switch, Anti-Ghosting, Double-Shot PBT Keycaps, Light Up Keyboard for PC Mac
  • Brilliant Color Illumination- With 11 unique backlights, choose the perfect ambiance for any mood. Adjust light speed and brightness among 5 levels for a comfortable environment, day or night. The double injection ABS keycaps ensure clear backlight and precise typing. From late-night tasks to immersive gaming, our mechanical keyboard enhances every experience
  • Support Macro Editing: The K671 Mechanical Gaming Keyboard can be macro editing, you can remap the keys function, set shortcuts, or combine multiple key functions in one key to get more efficient work and gaming. The LED Backlit Effects also can be adjusted by the software(note: the color can not be changed)
  • Hot-swappable Linear Red Switch- Our K671 gaming keyboard features red switch, which requires less force to press down and the keys feel smoother and easier to use. It's best for rpgs and mmo, imo games. You will get 4 spare switches and two red keycaps to exchange the key switch when it does not work.
  • Full keys Anti-ghosting- All keys can work simultaneously, easily complete any combining functions without conflicting keys. 12 multimedia key shortcuts allow you to quickly access to calculator/media/volume control/email
  • Professional After-Sales Service- We provide every Redragon customer with 24-Month Warranty , Please feel free to contact us when you meet any problem. We will spare no effort to provide the best service to every customer

For Bash’s complete read syntax and option behavior, see the GNU Bash Builtins reference.

Keyboard input is usually standard input

Although tutorials often call this “keyboard input,” read does not inherently know whether data came from a keyboard. Without redirection, it reads file descriptor 0, called standard input (stdin). Standard input can come from:

  • An interactive terminal and its keyboard.
  • A pipe from another command.
  • A file supplied with input redirection.
read -r value                 # normally reads stdin
printf '%sn' value | read -r value
read -r value < input.txt

The second example also illustrates a Bash pitfall: a loop or command in a pipeline can run in a subshell, so assignments may not remain available afterward. Read on for a safer pattern.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The safest default for a complete line

IFS= read -r value

This form is not ceremonial syntax:

  • IFS= prevents read from removing or splitting leading and trailing whitespace when assigning a complete line.
  • -r prevents backslashes from being interpreted as escape characters or as part of a backslash-newline continuation.

Use it for names, sentences, paths, copied text, regular expressions, and other values whose exact characters matter:

IFS= read -r -p "Enter a directory path: " directory
printf 'You entered: <%s>n' "$directory"

Without -r, an input such as C:Tempfiles may not be stored exactly as typed. Without IFS=, surrounding spaces can be removed or interpreted as field separators.

Displaying a prompt

The -p option displays a prompt without a trailing newline:

IFS= read -r -p "Project name: " project

Bash displays this prompt when input is coming from a terminal. If standard input is redirected or piped, the prompt may not appear. When you want explicit prompt control, write the prompt to standard error and read standard input separately:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
printf 'Project name: ' >&2
IFS= read -r project

Writing prompts to standard error keeps standard output available for data that another command may capture or pipe.

Checking whether input succeeded

read returns a success status when it obtains the requested input. It returns nonzero for conditions such as end-of-file, a timeout, an invalid file descriptor, or certain assignment errors.

if IFS= read -r -p "Enter your name: " name; then
    printf 'Hello, %s!n' "$name"
else
    printf 'No input was received.n' >&2
    exit 1
fi

An empty line is different from failed input. Pressing Enter can be a successful read whose value contains zero characters:

Rank #2
Sale
AULA F75 Pro Wireless Mechanical Keyboard,75% Hot Swappable Custom Keyboard with Knob,RGB Backlit,Pre-lubed Reaper Switches,Side Printed PBT Keycaps,2.4GHz/USB-C/BT5.0 Mechanical Gaming Keyboards
  • Tri-mode Connection Keyboard: AULA F75 Pro wireless mechanical keyboards work with Bluetooth 5.0, 2.4GHz wireless and USB wired connection, can connect up to five devices at the same time, and easily switch by shortcut keys or side button. F75 Pro computer keyboard is suitable for PC, laptops, tablets, mobile phones, PS, XBOX etc, to meet all the needs of users. In addition, the rechargeable keyboard is equipped with a 4000mAh large-capacity battery, which has long-lasting battery life
  • Hot-swap Custom Keyboard: This custom mechanical keyboard with hot-swappable base supports 3-pin or 5-pin switches replacement. Even keyboard beginners can easily DIY there own keyboards without soldering issue. F75 Pro gaming keyboards equipped with pre-lubricated stabilizers and LEOBOG reaper switches, bring smooth typing feeling and pleasant creamy mechanical sound, provide fast response for exciting game
  • Advanced Structure and PCB Single Key Slotting: This thocky heavy mechanical keyboard features a advanced structure, extended integrated silicone pad, and PCB single key slotting, better optimizes resilience and stability, making the hand feel softer and more elastic. Five layers of filling silencer fills the gap between the PCB, the positioning plate and the shaft,effectively counteracting the cavity noise sound of the shaft hitting the positioning plate, and providing a solid feel
  • 16.8 Million RGB Backlit: F75 Pro light up led keyboard features 16.8 million RGB lighting color. With 16 pre-set lighting effects to add a great atmosphere to the game. And supports 10 cool music rhythm lighting effects with driver. Lighting brightness and speed can be adjusted by the knob or the FN + key combination. You can select the single color effect as wish. And you can turn off the backlight if you do not need it
  • Professional Gaming Keyboard: No matter the outlook, the construction, or the function, F75 Pro mechanical keyboard is definitely a professional gaming keyboard. This 81-key 75% layout compact keyboard can save more desktop space while retaining the necessary arrow keys for gaming. Additionally, with the multi-function knob, you can easily control the backlight and Media. Keys macro programmable, you can customize the function of single key or key combination function through F75 driver to increase the probability of winning the game and improve the work efficiency. N key rollover, and supports WIN key lock to prevent accidental touches in intense games
if [[ -z $name ]]; then
    printf 'The name cannot be empty.n' >&2
fi

In other words:

  • Empty input: a line was read successfully, but it contained no characters.
  • EOF: no more input is available.
  • Timeout: the required input was not completed in time.
  • Invalid input: a line was read, but it does not satisfy your application’s rules.

For files whose last line may not end with a newline, use:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
while IFS= read -r line || [[ -n $line ]]; do
    printf 'Line: %sn' "$line"
done < input.txt

Reading multiple values

Multiple variable names make read split the line into fields using IFS:

read -r -p "Enter first and last name: " first last
printf 'First: %snLast: %sn' "$first" "$last"

This is suitable only when whitespace-separated fields are intended. If there are more fields than variables, the remaining text is assigned to the last variable. If there are fewer fields, remaining variables become empty.

read -r -p "Enter three numbers: " n1 n2 n3

For an arbitrary whitespace-separated list, use an indexed array:

read -r -a items
printf 'Item count: %dn' "${#items[@]}"
for item in "${items[@]}"; do
    printf '<%s>n' "$item"
done

The -a option assigns fields beginning at array index zero and clears the array’s previous elements. Do not use Bash field splitting as a CSV parser; quoted commas, embedded newlines, and escaping require a format-aware tool.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Validating user input

read captures text but does not decide whether that text is acceptable. Validate before using it.

Required values

while :; do
    if ! IFS= read -r -p "Username: " username; then
        printf 'nInput ended before a username was entered.n' >&2
        exit 1
    fi

    if [[ -n $username ]]; then
        break
    fi

    printf 'Please enter a username.n' >&2
done

Whole numbers

while :; do
    IFS= read -r -p "Enter a whole number: " number
    if [[ $number =~ ^[0-9]+$ ]]; then
        break
    fi
    printf 'Please enter digits only.n' >&2
done

For signed integers, use a pattern such as ^-?[0-9]+$. Do not perform arithmetic evaluation on unvalidated input:

# Do not do this before validation:
(( result = user_input + 1 ))

Yes/no answers

while :; do
    IFS= read -r -p "Continue? [y/n] " answer
    case ${answer,,} in
        y|yes) break ;;
        n|no)  exit 0 ;;
        *)     printf 'Please answer y or n.n' >&2 ;;
    esac
done

${answer,,} is Bash syntax for lowercasing a value. It is not portable to every shell, so keep the Bash requirement explicit.

Choice menus

Bash’s select builtin creates a numbered menu:

select choice in "Start" "Stop" "Quit"; do
    case $REPLY in
        1) printf 'Startingn'; break ;;
        2) printf 'Stoppingn'; break ;;
        3) exit 0 ;;
        *) printf 'Invalid selection.n' >&2 ;;
    esac
done

select is Bash-specific. The numeric response is stored in REPLY; the selected text is stored in choice.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Paths and destructive commands

Quote values and, where supported, use -- to mark the end of options:

Rank #3
Keychron C2 Full Size Wired Mechanical Keyboard, Brown Switch, Retro
  • The Keychron C2 (non-backlight version) is a 104 keys full size wired retro color keycaps mechanical keyboard made for Mac and Windows. Engineered to maximize your productivity with most popular full size layout with number pad.
  • With a layout optimized for Mac, the C2 has all necessary multimedia and function keys (Num Lock works with Windows only), while compatible with Windows, and comes with a dedicated Siri or Cortana key. Extra keycaps for both Mac and Windows operating systems are included.
  • Designed with reliability in mind, the C2 comes with USB Type-C wired connection with a braid cable, which ensures a constant power supply, and best to fit home and light gaming. Inclined bottom frame and 2 level adjustable feet (6˚ & 9˚) makes the C2 more comfortable to type.
  • The pre-installed tactile Keychron switch providing unrivaled tactile responsiveness with up to 50 million keystroke durable lifespan.
  • Outfitted the C2 Non-Backlight version with retro-inspired color scheme looks as good in the office as it does in the game room.
command -- "$value"

For example:

rm -rf -- "$directory"

Quoting prevents word splitting and pathname expansion, but it does not make a destructive operation safe. Validate the path, reject unexpected locations, and request explicit confirmation before deleting anything.

Password and secret input

Use -s to suppress character echo when reading a password from a terminal:

if IFS= read -r -s -p "Password: " password; then
    printf 'n'
else
    printf 'nUnable to read the password.n' >&2
    exit 1
fi

-s hides terminal echo; it does not encrypt the value, erase it from memory, prevent logging, or secure it against every form of exposure. Never print the captured password:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
# Never do this:
printf 'Password: %sn' "$password"

Avoid set -x while handling secrets because shell tracing can reveal commands and expanded values. Do not place passwords on command lines, where they may be exposed through shell history or process inspection. Environment variables and temporary files also have security trade-offs.

Timeouts and character input

Time-limited input

if IFS= read -r -t 10 -p "Enter a value within 10 seconds: " value; then
    printf 'Received: %sn' "$value"
else
    printf 'Input ended, timed out, or failed.n' >&2
fi

-t causes read to fail if the requested input is not completed within the specified time. Bash accepts fractional values such as 2.5. A failed read is not proof of a timeout: EOF and other failures are also possible. The option does not affect ordinary regular-file input.

Reading one or more characters

For a simple menu or confirmation:

if IFS= read -r -n 1 -p "Continue? [y/N] " answer; then
    printf 'n'
fi

-n reads up to the requested number of characters, but a delimiter or EOF can finish the read sooner. Bash’s -N option instead waits for exactly the requested number of characters, unless EOF or an error occurs:

read -r -N 4 code

Unlike -n, -N does not treat delimiter characters as an early stopping point and does not split the result using IFS.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Custom delimiters and NUL-separated input

Use -d to stop at a chosen delimiter:

IFS= read -r -d ':' value

An empty delimiter argument tells Bash to stop at a NUL byte:

IFS= read -r -d '' value

NUL-delimited records are useful when processing filenames from commands designed to handle arbitrary filenames. Ordinary interactive text is normally newline-delimited, so do not use this form unless the producer and consumer agree on the format.

Reading from files, pipes, and file descriptors

Use -u to read from a particular open file descriptor instead of standard input:

Rank #4
Redragon K521 Upgrade Rainbow LED Gaming Keyboard, 104 Keys Wired Mechanical Feeling Keyboard with Multimedia Keys, One-Touch Backlit, Anti-Ghosting, Compatible with PC, Mac, PS4/5, Xbox
  • 【Dreamy Rainbow Gaming Keyboard】K521 Gaming Keyboard Adopts a Different LED Backlight Design, Upgraded on the Traditional LED Backlight Effect, Making the Light More Penetrating, Giving You a More Dazzling Visual Effect, Making Your Gaming Process More Enjoyable
  • 【One Touch Opens & Visual Feast】The K521 Red Dragon Keyboard has a One-Touch on/off Lighting Button for Added Convenience. It also has a Three-Position Adjustable Breathing Mode and a Four-Position Adjustable Brightness Lighting Mode
  • 【Mechanical Feeling & Fast Tapping】The PC Keyboard Keys are Designed for Mechanical Feeling, Giving You a Better Feel During Use and the Ability to Trigger Keys Quickly, Allowing You to Win All Your Games
  • 【19 Keys Anti-Ghosting Keyboard】Anti-Ghosting Ensures Every Button Can Be Triggered. This Allows You to Trigger Key Combinations In The Game Accurately, And Each Skill Can Be Accurately Released to Increase Your Winning Rate. Redragon K521 Will Be Your Perfect Partner
  • 【12 Multimedia Combination Keys】The K521 Wired Gaming Keyboard is Equipped with 12 Multimedia Keys That Can Greatly Enhance Your Gaming/Office Efficiency and Make It More Convenient to Use
exec 3< input.txt
while IFS= read -r -u 3 line; do
    printf '%sn' "$line"
done
exec 3<&-

This is useful when a script reads a data file while keeping standard input available for a user:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
exec 3< users.txt
IFS= read -r -p "Enter a value: " value
IFS= read -r -u 3 first_user
exec 3<&-

Close descriptors when they are no longer needed. For simple file processing, redirection on the loop is often clearer:

while IFS= read -r line; do
    printf '%sn' "$line"
done < input.txt

Reading from the keyboard when standard input is redirected

If a script’s standard input is occupied by a pipe or file, an ordinary read will consume that data rather than waiting for the keyboard. On a normal terminal, read directly from /dev/tty:

IFS= read -r -p "Confirm: " answer </dev/tty

A more defensive approach first checks whether standard input is a terminal and falls back to file descriptor 3:

if [[ -t 0 ]]; then
    input_fd=0
else
    exec 3</dev/tty || {
        printf 'No interactive terminal is available.n' >&2
        exit 1
    }
    input_fd=3
fi

IFS= read -r -u "$input_fd" -p "Value: " value

if (( input_fd == 3 )); then
    exec 3<&-
fi

/dev/tty is normally available in a terminal session, but it may not exist or be usable in cron, services, containers without a TTY, or other noninteractive environments. A script should fail clearly or provide a noninteractive alternative rather than assuming a terminal exists.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Pipeline loops and subshells

This common pattern may not preserve last after the loop:

printf '%sn' one two |
while IFS= read -r item; do
    last=$item
done

printf '%sn' "$last"

In Bash execution contexts where the last pipeline component runs in a subshell, the assignment disappears when that subshell exits. Use process substitution when the loop must update variables in the current shell:

while IFS= read -r item; do
    last=$item
done < <(printf '%sn' one two)

printf '%sn' "$last"

Alternatively, redirect a loop from a file or use an array when that better matches the data model.

Readline editing and completion

For interactive tools, -e enables Bash Readline editing when standard input is a terminal:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
read -r -e -p "File: " file

You can pre-fill the editing buffer with -i:

read -r -e -i "default.txt" -p "File: " file

-E selects Bash’s default completion behavior, including programmable completion. These options are terminal-oriented and should not be assumed to work meaningfully for piped or automated input.

Best Value
Logitech MX Mechanical Wireless Illuminated Keyboard Tactile - Graphite
  • Tactile Quiet mechanical key switches with a satisfying tactile bump you feel - for precise feedback, reactive key reset, and less noise so your typing doesn't disturb those around you
  • Low-profile keys, more comfort: A keyboard layout designed for effortless precision, with a full-size form factor and low-profile mechanical switches for better ergonomics
  • Smart illumination: Backlit keys light up the moment your hands approach the cordless keyboard and automatically adjust to suit changing lighting conditions
  • Faster workflow, more customization: Customize Fn keys, assign backlighting effects, enable Flow cross-computer, multi-device control, and more in the improved Logi Options+ (1)
  • Multi-device, multi-OS: Pair MX Mechanical Bluetooth wireless keyboard with up to 3 devices on nearly any operating system via Bluetooth Low Energy or included Logi Bolt receiver(2)

A reusable required-input function

For a larger Bash script, a function can centralize prompting and validation:

prompt_required() {
    local prompt=$1
    local __resultvar=$2
    local answer

    while :; do
        IFS= read -r -p "$prompt" answer || return 1
        if [[ -n $answer ]]; then
            printf -v "$__resultvar" '%s' "$answer"
            return 0
        fi
        printf 'A value is required.n' >&2
    done
}

if prompt_required 'Name: ' name; then
    printf 'Hello, %sn' "$name"
fi

local limits temporary variables to the function. printf -v assigns the result without reparsing it as shell code. This function adds Bash concepts and may be unnecessary for a tiny script, but it gives a larger script consistent behavior for required prompts.

Common mistakes and fixes

Problem Better approach
Backslashes disappear Use IFS= read -r value.
Leading or trailing spaces disappear Use an empty IFS assignment for that read.
Input is split unexpectedly Read the complete line into one variable instead of using multiple variable names.
A prompt is missing in a pipeline Prompts are terminal-oriented; use printf ... >&2 and, when appropriate, read from /dev/tty.
The script appears to skip input Check whether a previous command consumed the line and whether [[ -t 0 ]] reports a terminal.
The final file line is skipped Use while IFS= read -r line || [[ -n $line ]].
User input breaks a command Quote expansions and use -- where supported.
User input executes as a command Never pass raw input to eval or construct a shell command for sh -c.

Never execute raw input

Input should be treated as data, not shell source:

# Unsafe:
read -r command
eval "$command"

# Also dangerous:
sh -c "$user_input"

If a user must choose an operation, map an allowed value to a fixed command:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
case $choice in
    start) systemctl start my-service ;;
    stop)  systemctl stop my-service ;;
    *)     printf 'Invalid choice.n' >&2; exit 2 ;;
esac

Quoting protects against many word-splitting and globbing bugs, but it does not make arbitrary shell evaluation safe.

Interactive prompts versus automation

Interactive input is convenient for humans but unsuitable for many cron jobs, CI pipelines, configuration-management runs, SSH commands without a terminal, and containers launched without a TTY.

For a script that supports both command-line use and interactive fallback:

name=${1-}

if [[ -z $name ]]; then
    IFS= read -r -p "Name: " name
fi

printf 'Hello, %sn' "$name"

For proper command-line options, use Bash’s getopts rather than prompting for every setting. Arguments, environment variables, configuration files, and standard input are usually better interfaces for automation. Prompt only when an interactive terminal is intentionally part of the design.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When to use read

  • Use IFS= read -r line for one complete line of text.
  • Use multiple variables only when whitespace-separated fields are intentional.
  • Use -a for a whitespace-separated list.
  • Use -s for basic hidden terminal entry, while remembering that it is not encryption.
  • Use -t when an interactive operation needs a deadline.
  • Use -u or /dev/tty when standard input is being used for something else.
  • Validate before arithmetic, filesystem operations, or selecting an action.
  • Prefer noninteractive arguments or getopts when another program will invoke the script.

Complete example

The following script combines successful reads, required-value validation, and silent secret entry:

#!/usr/bin/env bash

set -u

while :; do
    if ! IFS= read -r -p "Enter your name: " name; then
        printf 'nInput ended before a name was entered.n' >&2
        exit 1
    fi

    if [[ -n $name ]]; then
        break
    fi

    printf 'The name cannot be empty.n' >&2
done

if IFS= read -r -s -p "Enter a secret: " secret; then
    printf 'n'
else
    printf 'nUnable to read the secret.n' >&2
    exit 1
fi

printf 'Hello, %s!n' "$name"
# Use "$secret" only where necessary; never print it.

The first loop distinguishes a successful empty line from EOF and keeps prompting until a nonempty name is received. The second read suppresses terminal echo and prints a separate newline afterward because the prompt itself does not add one. The secret remains available to later code but is never displayed.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.