Reading User Input
Interactive scripts need to gather input from users during execution. The read command is your primary tool for this.
The read Command
Basic usage of read:
#!/bin/bash
echo "What is your name?"
read NAME
echo "Hello, $NAME!"
When executed, the script pauses at read and waits for user input.
Read with Prompt
Use -p to display a prompt on the same line:
#!/bin/bash
read -p "Enter your name: " NAME
echo "Hello, $NAME!"
This is cleaner than separate echo and read commands.
Read Options
The read command has many useful options:
| Option | Description |
|---|---|
-p "prompt" | Display prompt before reading |
-s | Silent mode (hide input, for passwords) |
-n N | Read only N characters |
-t N | Timeout after N seconds |
-r | Raw mode (don't interpret backslashes) |
-a array | Read into an array |
-d 'char' | Use character as delimiter instead of newline |
Silent Input for Passwords
Hide sensitive input with -s:
#!/bin/bash
read -sp "Enter password: " PASSWORD
echo # Add newline after hidden input
echo "Password received (${#PASSWORD} characters)"
Note: The -s flag hides what the user types.
Reading with Timeout
Don't wait forever for input:
#!/bin/bash
read -t 5 -p "Quick! Enter something (5 seconds): " ANSWER
if [ -z "$ANSWER" ]; then
echo "Too slow!"
else
echo "You entered: $ANSWER"
fi
Reading Limited Characters
Read exactly N characters:
#!/bin/bash
read -n 1 -p "Press any key to continue... "
echo # Newline
read -n 3 -p "Enter 3-letter code: " CODE
echo
echo "Code: $CODE"
Reading Multiple Variables
Read multiple values into multiple variables:
#!/bin/bash
echo "Enter first and last name:"
read FIRST LAST
echo "First: $FIRST"
echo "Last: $LAST"
# Input: "John Smith" -> FIRST=John, LAST=Smith
# Input: "John Paul Smith" -> FIRST=John, LAST="Paul Smith"
Extra words go into the last variable.
Exercise: Read User Input
Simulate reading input by setting a variable:
Reading into an Array
Read space-separated values into an array:
#!/bin/bash
read -p "Enter fruits (space-separated): " -a FRUITS
echo "You entered ${#FRUITS[@]} fruits:"
for fruit in "${FRUITS[@]}"; do
echo " - $fruit"
done
Using a Custom Delimiter
Read until a specific character:
#!/bin/bash
# Read until a comma
read -d ',' -p "Enter text (end with comma): " TEXT
echo "You entered: $TEXT"
The IFS Variable
IFS (Internal Field Separator) controls how read splits input:
#!/bin/bash
# Read CSV data
LINE="John,25,Engineer"
IFS=',' read -r NAME AGE JOB <<< "$LINE"
echo "Name: $NAME, Age: $AGE, Job: $JOB"
Raw Mode with -r
Always use -r to prevent backslash interpretation:
# Without -r (backslash is interpreted)
echo "Enter path:"
read PATH_VAR
# Input: C:\Users\name → PATH_VAR becomes "C:Usersname"
# With -r (backslash is literal)
read -r PATH_VAR
# Input: C:\Users\name → PATH_VAR becomes "C:\Users\name"
Best practice: Always use read -r unless you specifically need backslash interpretation.
Yes/No Confirmation
A common pattern for confirmations:
#!/bin/bash
read -p "Are you sure? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
echo "Proceeding..."
else
echo "Cancelled."
fi
Menu Selection
Create interactive menus:
#!/bin/bash
echo "Select an option:"
echo "1) Option One"
echo "2) Option Two"
echo "3) Exit"
read -p "Enter choice [1-3]: " CHOICE
case $CHOICE in
1) echo "You chose Option One" ;;
2) echo "You chose Option Two" ;;
3) echo "Goodbye!" ;;
*) echo "Invalid option" ;;
esac
The select Command
An easier way to create menus:
#!/bin/bash
PS3="Select a fruit: " # Custom prompt
select FRUIT in "Apple" "Banana" "Cherry" "Quit"; do
case $FRUIT in
"Apple") echo "You picked an apple!" ;;
"Banana") echo "You picked a banana!" ;;
"Cherry") echo "You picked a cherry!" ;;
"Quit") break ;;
*) echo "Invalid option" ;;
esac
done
Reading from a File
Use redirection to read from files:
#!/bin/bash
# Read first line of a file
read -r FIRST_LINE < /etc/hostname
echo "Hostname: $FIRST_LINE"
# Read all lines
while read -r LINE; do
echo "Line: $LINE"
done < file.txt
Exercise: Parse Delimited Data
Work with delimited input:
Best Practices
- Always use
-rto prevent backslash interpretation - Use
-pfor prompts instead of separate echo - Set timeouts for non-critical input with
-t - Hide passwords with
-s - Validate input before using it
- Provide default values when appropriate
#!/bin/bash
# Good read practices
# With all best practices
read -rp "Enter username: " USERNAME
read -rsp "Enter password: " PASSWORD
echo
# With timeout and default
read -rt 10 -p "Enter name [Guest]: " NAME
NAME="${NAME:-Guest}"
# Validate input
while true; do
read -rp "Enter a number: " NUM
if [[ "$NUM" =~ ^[0-9]+$ ]]; then
break
fi
echo "Invalid input. Please enter a number."
done
Key Takeaways
readpauses the script to get user input- Use
-p "prompt"to display a prompt - Use
-sfor password (hidden) input - Use
-t Nfor timeout after N seconds - Use
-n Nto read only N characters - Always use
-rfor raw input (no backslash interpretation) - Use
-a arrayto read into an array - Change
IFSto parse delimited data selectcreates interactive menus easily

