User Input

Static scripts are limited. Interactive scripts ask questions and respond.

The read Command

Terminal
$echo "What's your name?"
What's your name?
$read name
(waits for input)
$echo "Hello, $name!"
Hello, John!

read pauses, waits for input, stores it in the variable.

Prompt on Same Line

Terminal
$read -p "Enter your name: " name
Enter your name: John
$echo "Hello, $name"
Hello, John

-p displays a prompt without needing a separate echo.

Silent Input (Passwords)

Terminal
$read -sp "Password: " password
Password:
$echo
(newline after hidden input)
$echo "Password length: ${#password}"
Password length: 8

-s hides what the user types.

Read with Timeout

Terminal
$read -t 5 -p "Answer within 5 seconds: " answer
(times out after 5 seconds)

-t sets a timeout in seconds.

Read Multiple Values

Terminal
$echo "Enter first and last name:"
Enter first and last name:
$read first last
John Smith
$echo "First: $first, Last: $last"
First: John, Last: Smith

Multiple variables split on whitespace.

Default Values

Terminal
$read -p "Port [8080]: " port
Port [8080]:
$port=${port:-8080}
$echo "Using port: $port"
Using port: 8080

${var:-default} uses default if var is empty.

Yes/No Confirmation

hljs bash
#!/bin/bash

read -p "Delete all files? (y/n): " confirm

if [[ "$confirm" == "y" || "$confirm" == "Y" ]]; then
    echo "Deleting..."
else
    echo "Cancelled"
fi
Terminal
$./confirm.sh
Delete all files? (y/n): n Cancelled
hljs bash
#!/bin/bash

echo "Select an option:"
echo "1) Start server"
echo "2) Stop server"
echo "3) Show status"
echo "4) Exit"

read -p "Choice: " choice

case $choice in
    1) echo "Starting server..." ;;
    2) echo "Stopping server..." ;;
    3) echo "Server is running" ;;
    4) exit 0 ;;
    *) echo "Invalid option" ;;
esac

The select Command

Bash has a built-in select command for menus, but manual menus give you more control over formatting.

Validate Input

hljs bash
#!/bin/bash

while true; do
    read -p "Enter a number (1-10): " num

    if [[ "$num" =~ ^[0-9]+$ ]] && [ "$num" -ge 1 ] && [ "$num" -le 10 ]; then
        echo "You entered: $num"
        break
    else
        echo "Invalid. Try again."
    fi
done

Keep asking until valid input received.

Reading from Files

Terminal
$while read line; do
$ echo "Line: $line"
$done < file.txt
Line: first line Line: second line

read in a loop processes file line by line.

Knowledge Check

How do you hide user input (for passwords) with read?

Quick Reference

OptionPurpose
read varRead into variable
read -p "prompt" varShow prompt
read -s varHide input
read -t 5 varTimeout after 5 seconds
read -n 1 varRead single character
${var:-default}Default if empty

Key Takeaways

  • read variable captures user input
  • -p adds a prompt on the same line
  • -s hides input (for passwords)
  • -t sets a timeout
  • Use ${var:-default} for default values
  • Validate input before using it

Next: making decisions with conditionals.