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.



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
  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.


Navigate/Edit Input before sending

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:


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:


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:


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]


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

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:

read -p "Username: " username
read -s -p "Password: " password

# Simulate user validation (Replace with real validation in production)
if [[ "$username" == "admin" &amp;&amp; "$password" == "secret" ]]; then
  echo "Access granted."
  echo "Access denied."

This script prompts the user for a username and password, and then compares the entered values with predetermined credentials.

  1. The -p option prompts for the username.
  2. The -s option hides the input while prompting for the password.
  3. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *