Get 50% Discount Offer 26 Days

Recommended Services
Supported Scripts
WordPress
Hubspot
Joomla
Drupal
Wix
Shopify
Magento
Typeo3
How to Use Bash read Command: 10 Important Examples for Shell Scripting

The Bash read command is a highly versatile and essential tool for shell scripting in Linux. It allows you to seamlessly capture user input, process data from files, or handle interactive prompts. With its range of options, read enables dynamic and faster scripts that cater to various scenarios.

In this comprehensive guide, you’ll learn everything you need about the Bash read command with 10 practical examples to increase your scripting capabilities.

What is the Bash read Command?

The Bash read command is a built-in utility designed to accept input from the user, files, or standard input (stdin) and assign it to variables. This makes it an indispensable tool for creating interactive and dynamic scripts.

Key Applications:

  • Interactive Input: Capture real-time user input.
  • File Parsing: Read and process lines from Text files.
  • Custom Data Handling: Handle multi-line input or specific formats with ease.

Why It Matters:

The read command bridges the gap between static scripts and adaptable, user-driven workflows, allowing you to write smarter, more flexible code.

Why Use the Bash read Command?

The read command offers several advantages that make it a go-to tool for shell scripting:

  1. Interactive Scripts: Pause and collect user input during script execution.
  2. Dynamic Variable Assignment: Assign input to variables dynamically for flexibility.
  3. File Processing: Process data line by line.
  4. Advanced Input Options: Customize input handling with features like timeouts, hidden input, and character limits  

Key Features of the Bash read Command

Here’s a summary of the powerful features provided by the read command:

  • Prompt Messages: Display custom messages with the -p option.
  • Hidden Input: Use -s to hide sensitive information like passwords.
  • Timeouts: Avoid indefinite waits by setting time limits with -t.
  • Character Limits: Restrict input length using -n.
  • Custom Delimiters: Read input based on custom delimiters with -d.
  • Error Codes: Handle errors smartly with Exit codes.
  • Multi-Line Input: Capture multi-line data with -r and backslashes.

Basic Syntax of the read Command

The read command in Bash is a fundamental tool for capturing user input, making it important for interactive scripts. Its basic syntax is

read [options] [variable_name...]

Parameters:

  • options: Flags to modify behavior (e.g., -p for a prompt, -s for silent input).
  • variable_name: Variable(s) to store the input. If omitted, input is stored in the REPLY variable.

Example 1: Reading a Single Line of Input

This simple example demonstrates how to read a single line of user input.

#!/bin/bash

echo "Enter your name:"
read name
echo "Hello, $name!"

How It Works:

  • The read command is used to halt the execution of a Bash script and waits for user input. When the script reaches the read command, it stops and waits until the user types something and presses Enter. The input the user provides is then stored in a specified variable (in this case, name). This stored value can be accessed later in the script, allowing the program to use it in outputs or subsequent operations. This functionality makes Bash scripts more interactive, responding based on the user’s input at runtime.
Learn How to Pause and Interact with Bash Scripts Using the Read Command
  • The Text the user enters is captured and stored in the variable named name. Once the input is provided, the script continues its execution, and the stored value in the name can be used within the script. In this example, the script displays a greeting message using the input entered and combines it with the echo command. By referencing $name, the script dynamically inserts the user’s input into the output, displaying a personalized message such as “Hello, [entered name]!” This functionality allows for interactive, user-responsive scripts, enhancing the usability of Bash commands.
Learn How to Capture and Store User Input in Bash Scripts

Example 2: Reading Input into Multiple Variables

The read command can split input into multiple variables based on spaces or tabs.

#!/bin/bash

echo "Enter your first and last name:"
read first_name last_name
echo "Hello, $first_name $last_name!"

Key Points:

  • The read command in a Bash script automatically splits user input at whitespace characters, such as spaces or tabs. For example, if a user enters “John Doe” in response to a prompt, read will interpret “John” and “Doe” as two separate inputs, assigning them to different variables if multiple variables are specified. This feature allows for flexible user input handling, as each word can be assigned to a different variable. However, if more words are entered than there are variables, the remaining words are all assigned to the last variable.
Learn How to Split User Input into Multiple Variables in Bash Scripts
  • If the number of words the user enters exceeds the number of variables provided in the read command, Bash automatically assigns all remaining words to the final variable. For example, if you ask the user for a first and last name with read first_name last_name but they input “John Doe Smith,” “John” goes to first_name, while “Doe Smith” is stored in last_name. This functionality allows Bash to handle variable-length input gracefully, storing any overflow of words in the last specified variable for fast processing and readability.
Learn How to Handle Excess User Input with the Read Command in Bash Scripts

Example 3: Using -p to Display a Prompt

The -p option embeds a prompt directly within the read command.

#!/bin/bash

read -p "Enter your age: " age
echo "You are $age years old."

Why It’s Useful:

  • Using the -p option with the read command allows you to prompt the user directly within the read command, eliminating the need for a preceding echo statement to display the prompt. For example, read -p “Enter your age: ” age displays the prompt and simultaneously stores the user input in the age variable. This approach simplifies the code by reducing redundancy, making it cleaner and easier to follow. It also facilitates user interaction by keeping the prompt and input on the same line, enhancing the script’s usability and professionalism.
Learn How to Combine Prompts and Input with the Read Command
  • Combining the prompt and input handling into a single line with read-p makes the code more concise, improving readability and maintainability. In scripting, readability is crucial for long or complex scripts, allowing others (or yourself) to understand and modify the code if needed quickly. Thus, The- p option helps create cleaner, shorter scripts without compromising functionality. This minor simplification can significantly impact scripts with multiple prompts, making the overall structure easier.
Learn How to Combine Prompts and Input into a Single Line with the -p Option

Example 4: Hiding Input with -s

Hide sensitive input, like passwords, using the -s option.

#!/bin/bash

read -sp "Enter your password: " password
echo -e "\nPassword saved securely."

Applications:

  • With password prompts, read-s is most suitable as it masks the typed characters, thus providing an extra measure of security. This option is also used in scripts that need user credentials so that nobody watching the terminal while inputting the passwords will see.
Learn How to Use the read -s Command for Secure Password Prompts
  • The -s option then proves useful when one is required to input a password, API key, or other personal details. Because the input is concealed, the script becomes less vulnerable to accidental exposure and more suitable for environments that require privacy.
Using read -s for Secure Password Prompts

Example 5: Reading Input with a Timeout (-t)

Set a time limit for input to ensure scripts don’t hang indefinitely.

#!/bin/bash

read -t 10 -p "Enter your username (10 seconds): " username
if [ -z "$username" ]; then
  echo "Timeout: No input provided."
else
  echo "Hello, $username!"
fi

Use Cases:

  • The —t option in the read command assists in a scenario where a script cannot afford to wait for the user to enter forever. A timeout is used to continue the script with specific actions or to terminate it calmly if no action is initiated within the set time.
Understand How to Handle Timeouts in Bash Scripts
  • As with most command-line utilities, if the time elapsed between actions (like system configuration and security procedures) has to be kept to a minimum, the —t option overrides any delay in reading user input. When no response is received within the said timeframe, the script can automatically continue to the following instructions and keep any time-bound sequences efficient.
Create Time-Limited User Input Prompts with the -t Option

Example 6: Limiting Input Characters with -n

Restrict input to a specific number of characters with the -n option.

#!/bin/bash

read -n 5 -p "Enter a 5-character code: " code
echo -e "\nYour code is: $code"

Best For:

  • With the—n option, it is possible to set up a precise number of characters that should be read from the input stream. This makes the tool useful for reading data with standard formats, such as PIN codes. It eliminates situations whereby the user inputs a string of words in the wrong character limit, maybe by accident or on purpose, to defraud the system or its intended programmer.
Learn How to Enforce Fixed-Length Input with the -n Option
  • The—n option helps standardize data entry by limiting the input length. This functionality is proper whenever the format used must be system-wide, such as serial numbers or product codes. It prevents the user from entering an excessive number of characters than required, making the data processing process and validation efficient.
Fixed-Length Input in Bash Scripts

Example 7: Reading Input from a File

Process each line of a file with the read command.

Input File (names.txt):

John

Mary

Michael

Script:

#!/bin/bash

while read -r name; do
  echo "Hello, $name!"
done < names.txt

Why It’s Useful:

  • Reading files line by line using read in a loop is very effective. One prefers to read the file line by line and process each line, for example, applying some filter on the line, so it takes less memory space.
Efficiently Process Large Files with Bash Scripting
  • The read command effectively processes structured data like CSV or configuration files. Using scripts for each line in the file makes the format distinctively advantageous in handling fields and their corresponding values because it is efficient in extracting, manipulating, or displaying information according to every line in the format.
Extracting Information from Files with Bash

Example 8: Using -d to Define a Custom Delimiter

Change the delimiter for input handling using the -d option.

#!/bin/bash

read -d ":" -p "Enter colon-separated values: " input
echo "You entered: $input"

Applications:

  • Using the—d option with the read command allows you to specify a custom delimiter, making parse unique data formats easier. For example, with a colon-separated list,—d “:” treats each colon as a boundary, allowing the extraction of specific values and easy data handling.
Create Bash Scripts to Handle Custom Input Delimiters
  • The ability to define a custom delimiter helps process data that doesn’t follow standard whitespace-separated input. This makes it ideal for working with structured but unconventional formats, like log files or configuration data, where characters like colons, pipes, or semicolons may separate fields.
Using Custom Delimiters with the Read Command

Example 9: Reading Multiple Lines (-r and Backslashes)

Use -r and backslashes to capture multi-line input.

#!/bin/bash

echo "Enter your address (end with an empty line):"
address=""
while IFS= read -r line; do
  [ -z "$line" ] && break
  address+="$line\n"
done
echo -e "Your address:\n$address"

Key Features:

  • Using the read command in a loop allows you to capture multi-line input seamlessly. This is useful for input like addresses or paragraphs, where multiple lines are essential. The script collects the entire input block by appending each line to a variable until a break condition is reached.
Capturing Multi-Line Input with Bash Scripts
  • The—r option with read prevents the shell from interpreting escape characters (like n for new lines). This is useful whenever you require a precise match – for input in their rawest form – because characters will not be interpreted. Besides, it helps capture inputs like a backslash or any other unique character into the template.
Preventing Escape Character Interpretation with the Read Command

Example 10: Error Handling and Exit Codes

Use the Exit code of read for error handling.

#!/bin/bash

read -t 5 -p "Enter your name: " name
if [ $? -ne 0 ]; then
  echo "Timed out waiting for input."
else
  echo "Hello, $name!"
fi

Explanation:

  • $? stores the last command’s Exit status. When using read with a timeout (-t option), $? will hold 0 if successful or a non-zero value if the command times out or fails, which helps in error detection.
Checking Read Command Exit Status with $?
  • A non-zero Exit code from $? Usually, it signals an error. This is useful for identifying issues like timeouts in reading. If read fails to receive input within the specified time, $? returns a non-zero code. It will be executed, so the script returns a non-zero code, allowing it to manage the error and inform the user.
Checking Exit Status with $?

Conclusion

The Bash read command bridges the gap between creating elegant, interactive, and easy shell scripts. From collecting user input to processing files, it is a necessary and quite useful skill for every Linux user.

Key Takeaways:

  • Use read to enable real-time interaction in your scripts.
  • Explore advanced options like timeouts, character limits, and custom delimiters.
  • Leverage examples from this guide to build reliable, robust scripts.

Try it out with these examples to discover the unknown possibilities of the Bash read command to enhance your scripting skills.

About the writer

Vinayak Baranwal Article Author

Vinayak Baranwal wrote this article. Use the provided link to connect with Vinayak on LinkedIn for more insightful content or collaboration opportunities.

Leave a Reply

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

Lifetime Solutions:

VPS SSD

Lifetime Hosting

Lifetime Dedicated Servers