15 Examples for Linux read Command
The read
command in Linux allows you to read input from the standard input or from a file.
It allows you to receive data and assign it to variables. This tutorial will guide you through the different options of the read
command.
- 1 Reading input from the user
- 2 Reading input from a file
- 3 Specifying the delimiter
- 4 Read the values into an array (Multiple Values)
- 5 Navigate/Edit Input before sending
- 6 Edit Preloaded Text
- 7 Read up to NCHARS characters
- 8 Read exactly NCHARS characters
- 9 Output the string PROMPT before reading
- 10 Do not interpret backslashes as escape characters
- 11 Silent mode
- 12 Time out and Return Failure
- 13 Read from file descriptor
- 14 Security Considerations
- 15 Real-world Example
Reading input from the user
The basic use of the read
command is to take input from the user. Here’s a simple example:
echo "Please enter your name:" read name echo "Welcome, $name!"
When you run the above script, you will see:
Please enter your name:
You then enter your name, for example, “John,” and the output becomes:
Welcome, John!
Here, the echo
command prompts for your name, and the read
command stores your input in the variable name
. Finally, the echo
command prints a welcoming message with your entered name.
Reading input from a file
The read
command can be used to read input from a file line by line. Here’s how you can do it:
while IFS= read -r line do echo "Line: $line" done < file.txt
If file.txt
contains:
First line Second line
The output will be:
Line: First line Line: Second line
In this example, we use a while
loop and the read
command with the -r
option to read each line from file.txt
.
The IFS
variable is set to an empty value to preserve leading and trailing whitespaces, and each line is echoed to the console.
Specifying the delimiter
The read
command, by default, reads input until it encounters a newline character (\n
).
However, there are situations where you might want to change this default behavior, and this is where the -d
option comes into play.
With the -d
option, you can specify a delimiter other than the newline.
echo "Enter Text and to finish, write semicolon" read -d ';' text echo "The Text: $text"
In this example, the -d ';'
option tells the read
command to read input until it encounters a semicolon.
Read the values into an array (Multiple Values)
The -a
option allows you to read the input values into an array. Here’s an example:
echo "Please enter four numbers separated by space:" read -a numbers echo "You entered: ${numbers[0]}, ${numbers[1]}, ${numbers[2]}, ${numbers[3]}"
If you input:
10 20 30 40
The output will be:
You entered: 10, 20, 30, 40
The above example reads the input numbers and stores them in an array called numbers
. The values in the array are then accessed using array indices.
The -e
option in the read
command enables Readline support, allowing you to edit the input line with the arrow keys, delete key, etc.
echo "Please enter a sentence (use arrow keys to navigate):" read -e sentence echo "You entered: $sentence"
When you run this code, you can navigate through the text using the arrow keys, edit the text, and when you press Enter, it will display:
You entered: [Your edited sentence]
By enabling Readline, you provide an enhanced editing experience when collecting user input.
Edit Preloaded Text
With the -i
option, you can preload the input buffer with a specific text that the user can edit.
echo "Edit the following sentence:" read -e -i "The quick brown fox jumps over the lazy dog." sentence echo "You entered: $sentence"
When you run this command, the input line will be preloaded with:
The quick brown fox jumps over the lazy dog.
You can edit this sentence, and the final output will reflect your changes:
You entered: [Your edited sentence]
The -i
option in combination with -e
enables Readline and preloads the text, offering a powerful way to provide default input for editing.
Read up to NCHARS characters
The -n
option lets you specify the number of characters to read, rather than reading the entire line.
echo "Enter your 5-character username:" read -n 5 username echo "You entered: $username"
If you input:
James
The output will be:
You entered: James
This example limits the input to exactly 5 characters. The command returns after 5 characters are entered, without waiting for the Enter key.
Read exactly NCHARS characters
The -N
option reads exactly the specified number of characters, unlike the -n
option, which returns fewer characters if a newline is encountered.
echo "Enter exactly 5 characters:" read -N 5 exact_chars echo "You entered: $exact_chars"
If you input:
Linux
The output will be:
You entered: Linux
The above example reads exactly 5 characters, even if a newline is entered before the fifth character. This ensures a specific length for the input.
Output the string PROMPT before reading
With the -p
option, you can directly output a prompt string before reading the input.
read -p "Enter your name: " name echo "Welcome, $name!"
If you input:
Alice
The output will be:
Welcome, Alice!
Here, the -p
option is used to display a prompt directly from the read
command, eliminating the need for a separate echo
command.
Do not interpret backslashes as escape characters
By default, backslashes in the input are treated as escape characters. The -r
option disables this behavior.
echo "Enter a string with backslashes:" read -r backslashes echo "You entered: $backslashes"
If you input:
This is a test with backslashes: \test\example
The output will be exactly the same:
You entered: This is a test with backslashes: \test\example
Silent mode
The -s
option allows you to suppress the echoing of characters as they are typed. This is often used for entering passwords.
read -s -p "Enter your password: " password echo "Password entered successfully!"
When you enter your password:
[Your password]
Output:
Password entered successfully!
Your password will not be displayed on the screen.
Time out and Return Failure
The -t
option allows you to set a timeout for the read
command. If the input is not provided within the specified time, the command returns a failure.
read -t 5 -p "You have 5 seconds to enter your name: " name echo "Hello, ${name:-Guest}!"
If you enter your name within 5 seconds, the output will be:
Hello, [Your Name]!
If you don’t enter anything within 5 seconds, the output will be:
Hello, Guest!
The -t 5
option sets a 5-second timeout for the input. If the input is not provided in time, the default value “Guest” is used.
Read from file descriptor
The -u
option lets you specify a file descriptor to read from, instead of the standard input.
exec 3< file.txt read -u 3 line echo "Read from file descriptor: $line" exec 3<&-
If file.txt
contains:
This is a test line.
The output will be:
Read from file descriptor: This is a test line.
Here, you open file.txt
on file descriptor 3, then use the read -u 3
command to read from that descriptor. Finally, you close the file descriptor with exec 3<&-
.
Security Considerations
When using the read
command to handle user input, security must be a priority. There are two main aspects to consider:
Safeguarding against code injection: Be cautious when using input in commands without validation, as it will lead to code injection if not validated.
read -p "Enter a command: " cmd eval "$cmd"
This code is dangerous as it allows the execution of any command. You must validate and sanitize the input before executing.
Validating and sanitizing user input: Always validate input according to expected patterns and sanitize it if necessary.
read -p "Enter a number: " number if [[ ! "$number" =~ ^[0-9]+$ ]]; then echo "Invalid input. Please enter a number." exit 1 fi
This code ensures that the input is a number and rejects anything else.
By focusing on these aspects, you minimize the risks and protect the system from potential security breaches.
Real-world Example
Here’s a real-world example of how you can use the read
command to create a basic login script:
#!/bin/bash read -p "Username: " username read -s -p "Password: " password echo # Simulate user validation (Replace with real validation in production) if [[ "$username" == "admin" && "$password" == "secret" ]]; then echo "Access granted." else echo "Access denied." fi
This script prompts the user for a username and password, and then compares the entered values with predetermined credentials.
- The
-p
option prompts for the username. - The
-s
option hides the input while prompting for the password. - A simple if-statement checks if the entered credentials match the expected ones, providing appropriate feedback.
Note: This is a very simple example, and in a production environment, you should use proper authentication and security practices.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.