Introduction
Hello! In this article, we’ll learn about the read command.
read is a command for receiving input from users. Often used when creating interactive processes in shell scripts.
What is the read Command?
read is a command that stores keyboard input into variables.
For example, when you want to make scripts like “Please enter your name”, you use this. You can save what the user enters into a variable, so you can make interactive scripts.
Basic Syntax
|
|
Main Options
| Option | Description |
|---|---|
-p |
Display prompt message |
-s |
Don’t display input on screen (for passwords) |
-n number |
Read only specified number of characters |
-t seconds |
Set timeout |
Usage Examples
Example 1: Basic Usage
|
|
Output:
|
|
Example 2: With Prompt
|
|
Output:
|
|
Using -p lets you write it in one line without echo.
Example 3: Password Input (Hide Input)
|
|
Output:
|
|
The -s option hides input on screen.
Example 4: Store in Multiple Variables
|
|
Output:
|
|
Separated by spaces, stored in separate variables.
Example 5: Timeout Setting
|
|
Times out if not input within 5 seconds.
Tips & Notes
-
Whitespace handling: By default, leading/trailing spaces are removed
1 2read -p "Input: " var # Even if you input " test ", $var becomes "test" -
REPLY special variable: If you don’t specify a variable name, it automatically goes into
REPLY1 2read -p "Input: " echo "Input content: $REPLY" -
Read from file: Can also read from files with redirection
1 2read line < file.txt echo $line # First line of file is displayed -
Yes/No confirmation: Common pattern
1 2 3 4 5 6read -p "Continue? (y/n): " answer if [ "$answer" = "y" ]; then echo "Proceeding" else echo "Canceling" fi
Practical Usage
Interactive Script
|
|
Scripts that collect user info, stuff like that.
Confirmation Prompt
|
|
Often used to confirm before dangerous operations.
Password Input
|
|
Can be used when setting passwords.
Use in Loop
|
|
Can make simple interactive shells too.
Summary
In this article, we learned about the read command.
Key Points:
- Store user input in variables with
read -pfor prompt display,-sto hide input- Can split into multiple variables with spaces
- Essential when making interactive scripts
When you want interactive processing in shell scripts, this command is a must. Confirmation prompts, configuration input, etc. - lots of uses, so good to remember.
Keep learning Linux commands!