User Input
Static scripts are limited. Interactive scripts ask questions and respond.
The read Command
read pauses, waits for input, stores it in the variable.
Prompt on Same Line
-p displays a prompt without needing a separate echo.
Silent Input (Passwords)
-s hides what the user types.
Read with Timeout
-t sets a timeout in seconds.
Read Multiple Values
Multiple variables split on whitespace.
Default Values
${var:-default} uses default if var is empty.
Yes/No Confirmation
#!/bin/bash
read -p "Delete all files? (y/n): " confirm
if [[ "$confirm" == "y" || "$confirm" == "Y" ]]; then
echo "Deleting..."
else
echo "Cancelled"
fi
Menu Selection
#!/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
#!/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
read in a loop processes file line by line.
How do you hide user input (for passwords) with read?
Quick Reference
| Option | Purpose |
|---|---|
read var | Read into variable |
read -p "prompt" var | Show prompt |
read -s var | Hide input |
read -t 5 var | Timeout after 5 seconds |
read -n 1 var | Read single character |
${var:-default} | Default if empty |
Key Takeaways
read variablecaptures user input-padds a prompt on the same line-shides input (for passwords)-tsets a timeout- Use
${var:-default}for default values - Validate input before using it
Next: making decisions with conditionals.