Shell Script
33%
Course progress
2 of 9 topics done
Keep going, you are close!
3 topics in a row
2 of 9 topics done
CoursesdevopsShell ScriptInput and Variables
LessonΒ·3 of 9

Input and Variables

N/A9 lessons
1

ReadInput

πŸ“₯ Reading User Input

Read CommandUser InputInteractive ScriptsPromptsLevelDuration

πŸ“‹ Overview

🎯 Master Reading User Input in Shell Scripts

This guide covers the read command and its various options for creating interactive shell scripts that accept user input with prompts and validation.

πŸ” What This Guide Covers

  • πŸ“₯ Read Command Basics - Getting user input
  • πŸ’¬ Prompt Messages - Displaying prompts to users
  • πŸ” Secret Input - Reading passwords securely
  • 🎯 Read Options - Various flags and parameters
  • πŸ“Š Examples - Practical input scenarios
  • βœ… Best Practices - Input handling recommendations

πŸ“₯ What is the Read Command?

DefinitionFundamentals

The read command in Bash is used to get user input from the keyboard. It provides flexible options for prompting users and storing their input in variables. The read command is essential for creating interactive shell scripts.

Key Features:

  • Accepts user input from standard input
  • Stores input in variables
  • Supports prompt messages
  • Can hide input (for passwords)
  • Flexible with multiple options and arguments

πŸ”§ Read Command Syntax

SyntaxFormat

Basic Syntax

bash
read variable_name

Syntax with Options

bash
read [options] variable_name

Common Options

OptionDescriptionExample
-pDisplay prompt messageread -p "Enter name: " name
-sSilent mode (hide input)read -s password
-tTimeout in secondsread -t 5 input
-nRead N charactersread -n 1 char
-rRaw input (no escaping)read -r text

πŸ“₯ Basic Read Examples

Basic ExamplesSimple Usage

Example 1: Simple Read

bash
#!/bin/bash
# Script: simple_read.sh
# Purpose: Read a single value from user

read name
echo "Hello ${name}"

Usage:

bash
$ ./simple_read.sh
John
Hello John

Example 2: Read Multiple Values

bash
#!/bin/bash
# Script: multiple_read.sh
# Purpose: Read multiple values from user

read name
read age
echo "Hello ${name}, and your age is ${age}"

Usage:

bash
$ ./multiple_read.sh
John
25
Hello John, and your age is 25

Example 3: Read Without Variable (Using $REPLY)

bash
#!/bin/bash
# Script: reply_read.sh
# Purpose: Read input without specifying a variable

echo "Enter Name: "
read
echo "Name: $REPLY"

Output:

text
Enter Name: 
devopsgurupro
Name: devopsgurupro

Why It Works:

  • When you use read without specifying a variable name, the input is automatically stored in the special variable $REPLY
  • $REPLY is a built-in Bash variable that holds the last input from the read command
  • This is useful when you don't need to store the value in a named variable
  • You can access the input using $REPLY anywhere in your script
  • If you call read again without a variable, $REPLY will be overwritten with the new input

πŸ’¬ Read with Prompt Messages

PromptsUser Guidance

Example 1: Single Prompt

bash
#!/bin/bash
# Script: prompt_read.sh
# Purpose: Read with prompt message

read -p "Please enter your name: " name
echo "Hello ${name}"

Output:

text
Please enter your name: devopsgurupro
Hello devopsgurupro

Example 2: Multiple Prompts

bash
#!/bin/bash
# Script: user_info.sh
# Purpose: Collect user information

read -p "Please enter your name: " name
read -p "Please enter your age: " age
read -p "Please enter your city: " city

echo "Name: ${name}"
echo "Age: ${age}"
echo "City: ${city}"

Output:

text
Please enter your name: devopsgurupro
Please enter your age: 25
Please enter your city: New York
Name: devopsgurupro
Age: 25
City: New York

πŸ” Reading Secret Input (Passwords)

SecurityHidden Input

Example 1: Simple Password Input

bash
#!/bin/bash
# Script: password_read.sh
# Purpose: Read password securely

read -p "Please enter your password: " -s password
echo ""
echo "Password received (length: ${#password})"

Output:

text
Please enter your password: 
Password received (length: 8)

Example 2: Username and Password

bash
#!/bin/bash
# Script: login.sh
# Purpose: Read username and password

read -p "Enter Username: " username
read -sp "Enter Password: " password
echo ""

echo "Username: ${username}"
echo "Password: ******* (hidden)"

Output:

text
Enter Username: devopsgurupro
Enter Password: 
Username: devopsgurupro
Password: ******* (hidden)

πŸ“Š Complete Interactive Script Examples

Complete ExamplesReal World

Example 1: User Registration Form

bash
#!/bin/bash
# Script: registration.sh
# Purpose: Collect user registration information

echo "=== User Registration Form ==="
read -p "Enter your name: " name
read -p "Enter your email: " email
read -p "Enter your age: " age
read -sp "Enter your password: " password
echo ""

echo ""
echo "=== Registration Summary ==="
echo "Name: ${name}"
echo "Email: ${email}"
echo "Age: ${age}"
echo "Password: ******* (hidden)"

Output:

text
=== User Registration Form ===
Enter your name: devopsgurupro
Enter your email: [email protected]
Enter your age: 25
Enter your password: 

=== Registration Summary ===
Name: devopsgurupro
Email: [email protected]
Age: 25
Password: ******* (hidden)

Example 2: Interactive Menu

bash
#!/bin/bash
# Script: menu.sh
# Purpose: Create an interactive menu

echo "=== Main Menu ==="
echo "1. Option One"
echo "2. Option Two"
echo "3. Option Three"
read -p "Select an option (1-3): " choice

case $choice in
    1)
        echo "You selected Option One"
        ;;
    2)
        echo "You selected Option Two"
        ;;
    3)
        echo "You selected Option Three"
        ;;
    *)
        echo "Invalid option"
        ;;
esac

Example 3: Confirmation Prompt

bash
#!/bin/bash
# Script: confirm.sh
# Purpose: Ask for user confirmation

read -p "Do you want to continue? (yes/no): " response

if [ "$response" = "yes" ]; then
    echo "Continuing..."
else
    echo "Cancelled."
fi

🎯 Read Command Options

OptionsAdvanced Usage

Example 1: Timeout Option

bash
#!/bin/bash
# Script: timeout_read.sh
# Purpose: Read with timeout

read -t 5 -p "Enter something (5 seconds): " input

if [ -z "$input" ]; then
    echo "No input provided (timeout)"
else
    echo "You entered: ${input}"
fi

Example 2: Read N Characters

bash
#!/bin/bash
# Script: char_read.sh
# Purpose: Read specific number of characters

read -n 1 -p "Press any key to continue: " key
echo ""
echo "You pressed: ${key}"

Example 3: Raw Input

bash
#!/bin/bash
# Script: raw_read.sh
# Purpose: Read raw input without escaping

read -r -p "Enter path (with backslashes): " path
echo "Path: ${path}"

Example 4: Read into Array

bash
#!/bin/bash
# Script: array_read.sh
# Purpose: Read multiple values into an array

read -p "Enter names as per your choice: " -a names
echo "You have entered names: ${names[0]}, ${names[1]}, ${names[2]}"

Output:

text
Enter names as per your choice: dgpro wahid sameer
You have entered names: dgpro, wahid, sameer

Explanation:

  • -a flag reads input into an array variable
  • Each word separated by space becomes an array element
  • Access array elements using ${array[index]}
  • ${names[0]} = first name (dgpro)
  • ${names[1]} = second name (wahid)
  • ${names[2]} = third name (sameer)

βœ… Best Practices

Best PracticesStandards
  • Always use -p flag to display clear prompts
  • Use -s flag for sensitive information like passwords
  • Validate user input before using it
  • Provide clear instructions to users
  • Use meaningful variable names
  • Handle empty input gracefully
  • Use quotes around variables: "${variable}"
  • Test scripts with various inputs
  • Provide default values when appropriate

πŸ”— Navigation

Navigation

⬅️ Previous: Module 2: System-Defined Variables

πŸ“ Current Location: Reading User Input (You are here)

➑️ Next Step: Command-Line Arguments

πŸ—ΊοΈ Full Path: Module 3: Variables & Input β†’ Reading User Input β†’ Command-Line Arguments β†’ Command Output β†’ Read-Only Variables β†’ String Conversion β†’ Substring Operations β†’ Default Values β†’ Arithmetic Operations


πŸ“š Additional Resources

ResourcesDocumentation

Read Input Mastery

πŸŽ‰ Excellent! Reading User Input Complete! πŸŽ‰

➑️ Continue to Conditional Statements