Mastering User Input in Bash Scripts
Every interactive program needs to get input from users. In Bash, the read command is your primary tool for capturing user input and storing it in variables. This guide will show you everything you need to know about getting user input effectively.
The read Command: Your Input Gateway
The read command is Bash’s built-in tool for getting input from users. It pauses script execution and waits for the user to type something and press Enter.
Basic Syntax
read variable_nameSimple Example
read name# User types: John# Variable $name now contains: JohnHow read Works
Single Variable Input
When you provide one variable name, read captures the entire line:
read user_inputHello World! # User enters this# $user_input = "Hello World!"Multiple Variables Input
When you provide multiple variable names, read splits the input by whitespace:
read name age cityJohn 30 London # User enters this# $name = "John"# $age = "30"# $city = "London"Word Splitting Rules
- Default delimiter: Whitespace (spaces, tabs)
- IFS variable: Controls how input is split
- Last variable: Gets all remaining words
read first second thirdone two three four five# $first = "one"# $second = "two"# $third = "three four five" # All remaining wordsThe REPLY Variable
If you don’t specify a variable name, read uses the predefined REPLY variable:
read100 # User enters this# $REPLY = "100"Adding Prompts with -p Option
The -p option displays a prompt message before waiting for input:
read -p "Enter your name: " name# Displays: Enter your name:# Then waits for inputPractical Example: IP Blocker Script
#!/bin/bashread -p "Enter the IP address or domain to block: " IPsudo iptables -I INPUT -s $IP -j DROPHiding Input with -s Option
The -s option suppresses echo, perfect for passwords:
read -s -p "Enter password: " password# User types: secret123# Nothing appears on screen# $password = "secret123"Complete read Options Reference
| Option | Description |
|---|---|
-p "prompt" | Display a prompt |
-s | Silent mode (no echo) |
-a array | Read into an array |
-n num | Read specific number of characters |
-t seconds | Timeout after N seconds |
-r | Raw input (backslashes not interpreted) |
Real-World Examples
1. Interactive Configuration
#!/bin/bashread -p "Database host [localhost]: " db_hostdb_host=${db_host:-localhost} # Default value
read -p "Database name: " db_nameread -p "Username: " db_userread -s -p "Password: " db_passecho # New line after hidden input2. Menu Selection
#!/bin/bashecho "1. Start service"echo "2. Stop service"echo "3. Restart service"read -p "Choose an option: " choice
case $choice in 1) echo "Starting..." ;; 2) echo "Stopping..." ;; 3) echo "Restarting..." ;; *) echo "Invalid option" ;;esac3. Validation Loop
#!/bin/bashwhile true; do read -p "Enter yes or no: " answer if [[ "$answer" == "yes" || "$answer" == "no" ]]; then break fi echo "Please enter 'yes' or 'no'"doneAdvanced Techniques
Reading into an Array
read -a colorsred green blue # User enters this# colors[0] = "red"# colors[1] = "green"# colors[2] = "blue"Character Limit
read -n 3 -p "Enter 3 digits: " digits# User can only type 3 charactersTimeout
read -t 5 -p "You have 5 seconds to respond: " response# Script continues after 5 seconds if no inputRaw Mode
read -r -p "Enter path: " path# Backslashes are treated as literal charactersCommon Pitfalls and Solutions
Problem: Spaces in Input
# This won't work as expected:read first lastJohn Doe# $first = "John", $last = "Doe"
# Solution for full name:read -p "Enter name: " full_nameJohn Doe# $full_name = "John Doe"Problem: Empty Input
read -p "Enter value: " value# User just presses Enter# $value is empty
# Solution with validation:while [[ -z "$value" ]]; do read -p "Enter value (cannot be empty): " valuedoneProblem: Special Characters
read -p "Enter filename: " filenamefile with spaces.txt# This can cause issues in commands
# Solution: Always quote variablestouch "$filename"Best Practices
- Always provide clear prompts - Tell users what you expect
- Use defaults when possible - Show them in brackets
- Validate input - Don’t trust user input
- Use
-sfor sensitive data - Passwords, API keys - Quote your variables - Prevent word splitting issues
- Provide feedback - Confirm what was entered
Summary
read- The primary command for user input-p- Adds a prompt message-s- Hides input (for passwords)REPLY- Default variable when none specified- Multiple variables - Splits input by whitespace
- Always quote -
$variableshould be"$variable"
What’s Next?
Now that you know how to get user input, you’re ready to learn about special variables and positional parameters - another powerful way to pass data to your scripts!