How to Read User Input in Bash: Simple Guide
In bash, you can read user input using the
read command followed by a variable name to store the input. For example, read name waits for the user to type something and saves it in the variable name.Syntax
The basic syntax to read user input in bash is:
read variable_nameHere, read waits for the user to type input and press Enter. The input is then stored in variable_name. You can also use options like -p to show a prompt message.
bash
read variable_name
Example
This example asks the user for their name and then greets them using the input.
bash
echo "What is your name?" read name echo "Hello, $name!"
Output
What is your name?
John
Hello, John!
Common Pitfalls
One common mistake is forgetting to prompt the user, which can confuse them. Another is not quoting variables when using them, which can cause word splitting or errors if the input has spaces.
Also, using read without a variable stores input in the default variable REPLY, which might be unexpected.
bash
echo "Enter your city:" read city # Wrong: echo Hello, $city # Right: echo "Hello, \"$city\""
Quick Reference
| Command | Description |
|---|---|
| read variable | Reads input into variable |
| read -p "Prompt" variable | Shows prompt before reading input |
| read -s variable | Reads input silently (no echo) |
| read -t seconds variable | Times out after seconds if no input |
| read without variable | Stores input in REPLY variable |
Key Takeaways
Use the read command followed by a variable to get user input in bash.
Always prompt the user so they know what to enter.
Quote variables when using them to avoid issues with spaces.
Use options like -p to show prompts and -s for silent input.
If no variable is given, input is stored in the REPLY variable.