How to Use Read Command in Bash: Syntax and Examples
The
read command in bash reads a line of input from the user or a file and stores it in a variable. Use read variable_name to save the input into variable_name. It is commonly used to get user input during script execution.Syntax
The basic syntax of the read command is:
read [options] variable_name
Here, variable_name is where the input will be stored. If no variable is given, input is stored in the default variable REPLY.
Common options include:
-p: Prompt the user with a message.-r: Read raw input, backslashes are not treated specially.-t: Timeout after a number of seconds.
bash
read variable_name
Example
This example asks the user for their name and then prints a greeting using the input.
bash
echo "Enter your name:" read name echo "Hello, $name!"
Output
Enter your name:
John
Hello, John!
Common Pitfalls
One common mistake is not using -r when reading input that may contain backslashes, causing unexpected behavior.
Another is forgetting to prompt the user, which can confuse them.
Also, if you read multiple variables but input has fewer words, some variables remain empty.
bash
echo "Enter a path:" read path echo "You entered: $path" # Better to use: echo "Enter a path:" read -r path echo "You entered: $path"
Quick Reference
| Option | Description |
|---|---|
| -p | Display a prompt before reading input |
| -r | Read raw input, do not treat backslashes specially |
| -t seconds | Timeout after specified seconds |
| variable_name | Name of variable to store input |
Key Takeaways
Use
read variable_name to get user input into a variable.Add
-p to show a prompt message before input.Use
-r to read raw input and avoid backslash issues.If no variable is given, input is stored in
REPLY by default.Remember to handle empty or missing input to avoid script errors.