Class 18 of 37 • Shell Scripting Fundamentals \t\t\t\t

Read Command in Linux Shell Scripting - User Input, Flags & Examples

The read command is a fundamental built-in shell utility in Linux used to capture interactive keyboard input from the user or read data stream lines from a file or pipe. It splits the input line into words based on the Internal Field Separator ($IFS) and assigns them to the specified variable names.

Basic Syntax & Common Beginner Mistake

The syntax for capturing user input is:

read variable_name
Common Exam Trap: Never put a dollar sign ($) before the variable name in a read statement!
read $fname × (WRONG: expands $fname before reading)
read fname ✓ (CORRECT: stores user input into variable fname)

Basic Name Prompt Example

#!/bin/bash
echo "Enter Your First Name:"
read fname

echo "Enter Your Last Name:"
read lname

echo "Welcome - $fname $lname"

Powerful Command Options of read

Modern Bash provides powerful flags that eliminate the need for extra echo commands and make terminal applications secure and responsive:

Flag

Name

Description & Use Case

-p "prompt"

Prompt

Outputs the prompt string directly on the same line without needing a preceding echo -n.

-s

Silent

Suppresses terminal echoing. Ideal for secure password, PIN, or confidential token entry.

-t <seconds>

Timeout

Times out and aborts if user does not press Enter within the specified number of seconds.

-n <chars>

Number of Chars

Returns immediately once N characters are pressed without waiting for the Enter key.

-a <array>

Array

Reads space-separated tokens directly into an indexed array.

-r

Raw Mode

Disables backslash escaping so backslashes are preserved as literal characters.

Detailed Code Examples

1. Inline Prompting with -p and Silent Password with -s

#!/bin/bash
# Prompting inline
read -p "Enter System Username: " user

# Silent entry for passwords
read -s -p "Enter Secret Password: " pass
echo "" # Add a blank newline after silent input

echo "Authentication check initialized for: $user"

2. Timeout Prompting with -t

#!/bin/bash
# Prompt with 5-second automatic timeout
if read -t 5 -p "Do you want to proceed with upgrade? [y/n]: " ans; then
    echo -e "\nYou selected: $ans"
else
    echo -e "\n[TIMEOUT] No response within 5 seconds. Defaulting to No."
fi

3. Single-Key Response with -n 1

#!/bin/bash
# Instant keypress without pressing Enter
read -n 1 -p "Press any key to continue..." key
echo -e "\nResuming execution..."

4. Reading Space-Separated Values into an Array (-a)

#!/bin/bash
read -p "Enter your top 3 programming languages: " -a langs

echo "First choice : ${langs[0]}"
echo "Second choice: ${langs[1]}"
echo "Third choice : ${langs[2]}"
echo "Total listed : ${#langs[@]}"

Reading Files Line-by-Line using read -r

A universal task in Linux administration and university practical exams is iterating through a text file line-by-line. The safest and most robust pattern combines while, IFS=, and read -r:

#!/bin/bash
# read_file.sh: Safely process file lines
file="/etc/resolv.conf"

if [ ! -f "$file" ]; then
    echo "File not found: $file"
    exit 1
fi

line_num=1
# IFS= prevents trimming of leading/trailing spaces
# -r prevents backslash interpretation
while IFS= read -r line; do
    echo "Line $line_num: $line"
    line_num=$(( line_num + 1 ))
done < "$file"

Lab Practice: Secure Interactive Login Gatekeeper

Problem: Write an interactive login script that takes username, silent password, validates credentials, enforces a 15-second timeout, and asks for confirmation using read -n 1.

#!/bin/bash
# login_gatekeeper.sh: Secure Authentication Simulation

CORRECT_USER="admin"
CORRECT_PASS="Secret123"

echo "========================================="
echo "   SECURE SERVER ACCESS AUTHORIZATION   "
echo "========================================="

# 1. Prompt username with 15-second timeout
if ! read -t 15 -p "Username: " entered_user; then
    echo -e "\n[ERROR] Session timed out. Connection closed."
    exit 1
fi

# 2. Prompt silent password
read -s -t 15 -p "Password: " entered_pass
echo "" # Print newline

# 3. Validate credentials
if [ "$entered_user" = "$CORRECT_USER" ] && [ "$entered_pass" = "$CORRECT_PASS" ]; then
    echo -e "\e[32m[ACCESS GRANTED] Welcome, Administrator!\e[0m"
    read -n 1 -p "Launch terminal session now? (y/n): " confirm
    echo ""
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        echo "Launching root shell session..."
    else
        echo "Session aborted by user."
    fi
else
    echo -e "\e[31m[ACCESS DENIED] Invalid username or password.\e[0m"
    exit 2
fi

Frequently Asked Questions (FAQs)

read requires the identifier of the variable where the data should be assigned. Putting a dollar sign causes parameter expansion before read runs, causing errors or losing the input.
When no variable name is provided, Bash automatically stores the captured line in the default built-in environment variable $REPLY.
Use read -s -p "Enter Password: " my_pass. The -s flag turns off terminal echo, hiding typed characters from onlookers.
The -r flag disables backslash escaping, ensuring path characters like \ are read literally rather than altering data.

Next Step in Your Linux Learning Path:

Perform arithmetic, relational tests, and file inspections in Class 19: Operators in Shell Scripting.

Continue to Class 19: Operators in Shell Scripting → Previous: ← Echo Command | Full Syllabus

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!