read
Command in Linux: Reading User Input
Summary
The read
command in Linux is a powerful built-in command that reads input from the user or a file and assigns it to shell variables. It's an essential tool for creating interactive shell scripts and processing data from various sources.
Introduction
The read
command is used to take input from standard input (usually the keyboard) or a file descriptor and assign it to a variable. This allows you to create scripts that can interact with users, process input from files, or perform various tasks based on user-provided values. It is a fundamental command for creating dynamic and responsive scripts.
Use case and Examples
Reading User Input into a Variable
This example prompts the user to enter their name, stores it in thename
variable, and then greets the user using the entered name. Reading Multiple Values at Once
read -p "Enter your first and last name: " first last
echo "First name: $first"
echo "Last name: $last"
first
and last
variables respectively. Reading Input with a Timeout
read -t 5 -p "Enter a value within 5 seconds: " value
if [ -z "$value" ]; then
echo "Timeout! No input received."
else
echo "You entered: $value"
fi
value
variable will be empty, and the script will print a timeout message. Reading Input Silently (without Echoing to the Terminal)
read -s -p "Enter your password: " password
echo # Move to the next line after the input
echo "Password accepted."
echo
command after the read
command is used to move the cursor to the next line for better readability. Reading from a File
This example reads each line from theinput.txt
file and processes it within the loop. Commonly used flags
Flag | Description | Example |
---|---|---|
-p | Displays a prompt to the user before reading input. | read -p "Enter your age: " age |
-t | Sets a timeout (in seconds) for reading input. If no input is received within the specified time, the command returns with a non-zero exit status. | read -t 10 -p "Enter a value: " value |
-s | Reads input silently, without displaying it on the terminal (useful for passwords). | read -s -p "Enter your password: " password |
-n | Reads only a specified number of characters from the input. | read -n 5 -p "Enter a 5-character code: " code |
-d | Specifies a delimiter character. read will stop reading input when the delimiter is encountered. | read -d ":" -p "Enter a value ending with a colon: " value |
-r | Prevents backslash escapes from being interpreted. Useful when reading raw input that might contain backslashes. | read -r -p "Enter a path: " path |