How to Use the Bash Read Command

Updated on November 1, 2024
How to Use the Bash Read Command header image

Introduction

The Bash read command is a built-in command for capturing user input. The command reads text from the standard input and assigns the value to one or more variables. You can combine the bash read command with conditional statements and loops to validate user input, read file contents, and perform specific tasks in a script.

This article explains how to use the Bash read command. You'll use the command to create variables, read files, and validate user input in a shell or Bash script environment.

The Bash Read Command Syntax

The following is a basic read command syntax in Bash.

read [options] [var_name]

In the above command:

  • [options]: Includes optional flags that modify the command's behavior.
  • var_name: Includes the variable name that stores the input data.

The read command supports the following options:

  • -p: Displays a prompt before capturing the user input.
  • -s: Enables silent mode and hides input characters.
  • -n: Limits the number of input characters.
  • -t: Times out the input prompt after a specific number of seconds if the command receives no input.
  • -a: Stores the input into an array.
  • -r: Prevent backslashes (\) from being interpreted by the shell as escape or special characters,

The read command also supports multiple input values. You can store these values using separate variables with the following syntax.

read [options] [var_name] [var_name] [var_name]

To explore more on handling multiple conditions in Bash scripts, check out our guide on the bash case statement for effective pattern matching and control flow.

Capture User Input Using the Read Command

Follow the steps below to use the read command to capture user input in a Bash shell environment.

  1. Capture user input using the What's your name prompt and store the value in a name variable.

    console
    $ read -p "What's your name:" name
    

    Enter John Doe when prompted and press Enter to store the input in the name variable.

  2. Print the variable using the echo command.

    console
    $ echo $name
    

    Output:

    John Doe
  3. Run the following read command to store the user input in multiple variables, such as var1, var2, and var3.

    console
    $ read -p "Enter the Input Values:" var1 var2 var3
    

    Enter a string, such as Hello World! This_Works separated by spaces when prompted.

  4. Print the value of each variable.

    console
    $ echo $var1 $var2 $var3
    

    Output:

    Hello World! This_Works

    The bash read command assigns any extra values to the last variable when input values exceed the available variables. For example, with an input value such as Hello World! This_works in bash, the script assigns This_works in bash value to the last var3 variable.

Use the Bash Read Command with Redirections

The read command works with STDIN (Standard Input) by default. You can redirect other commands' outputs to the read command for processing and storage in a variable. This approach is important especially when working with files. Follow the steps below to use the read command with redirections.

  1. Create a new greet variable using the read command and a Hello World! Greetings from Vultr string <<< redirection.

    console
    $ read greet <<< "Hello World! Greetings from Vultr"
    
  2. Print the greet variable.

    console
    $ echo $greet
    

    Output:

    Hello World! Greetings from Vultr
  3. Create a new greeting variable and redirect its value to the read command.

    console
    $ greeting="Hello World! Bash works!"; read greet <<< "$greeting"; echo $greet
    

    Output:

    Hello World! Bash works!
  4. Create a new readme.txt file to use with the read command.

    console
    $ nano readme.txt
    
  5. Add the following contents to the readme.txt file.

    text
    Hello World!
    Greetings from Vultr.
    This is a sample README script
    

    Save and close the file.

  6. Display the contents of the readme.txt file using the read command and a while loop.

    console
    $ i=1; while read -r line; do echo "$i: $line"; ((i++)); done < readme.txt
    

    The above while loop uses the read command to display all lines in the readme.txt input file. The loop increments the i variable using the ((i++)) statement to number each line in the output.

    Output:

    1: Hello World!
    2: Greetings from Vultr.
    3: This is a sample README script

Use IFS and the Read Command to Split Input

IFS (Internal Field Separator) is a built-in Bash variable that splits characters into separate strings or fields. IFS enables the read command to split multiple inputs using spaces, tabs, and newlines delimiters by default. In the following steps, use IFS to enable other characters as delimiters to split user input with the read command.

IFS uses the following inline syntax with the read command unless you specify a delimiter in the global variable.

IFS='delimiter' read [options] [var_name]
  1. Input a new string, such as Hello World! This_works separated by spaces using the read command to split and store the values in multiple variables.

    console
    $ read var1 var2 var3 <<< "Hello World! This_works"
    

    By default, IFS uses spaces as the default delimiter for the read command.

  2. Print the value of each variable.

    console
    $ echo $var1 $var2 $var3
    

    Output:

    Hello World! This_works
  3. Set a new IFS delimiter, such as : to modify the read command's split method.

    console
    $ IFS=':'
    
  4. Input the Hello World! This_works string again.

    console
    $ read var1 var2 var3 <<< "Hello World! This_works"
    
  5. Print the value of the first variable. This time, the read command assigns the text to the first variable because you changed the delimiter.

    console
    $ echo $var1
    

    Output:

    Hello World! This_works
  6. Input the Hello:World:This_works string again and separate the string using the : delimiter.

    console
    $ read var1 var2 var3 <<< "Hello:World:This_works"
    
  7. Print the value of the first variable again.

    console
    $ echo $var1
    

    Output:

    Hello
  8. Print the value of each variable.

    console
    $ echo $var1 $var2 $var3
    

    Output:

    Hello World This_works
  9. Use IFS and the read command with multiple delimiters such as :, _, and - to split the input.

    console
    $ echo 'Hello:World-This_works.' | (IFS=":-_-" read -r var1 var2 var3; echo -e "$var1 $var2 $var3")
    

    Output:

    Hello World This_works.
  10. Reset IFS to the default delimiter settings.

    console
    $ IFS=$' \t\n'
    

Use the Read Command with Arrays in Bash

The bash read command stores multiple values into arrays using the -a option and splits the input using the default delimiter. Follow the steps below to use the read command with arrays in Bash.

  1. Input a new Hello World! This Works string value and store the input in a new_array array.

    console
    $ read -a new_array <<< "Hello World! This Works"
    
  2. Print all elements in the array.

    console
    $ echo "${new_array[@]}"
    

    Output:

    Hello World! This Works
  3. Create a new del_array array and set : as the delimiter using IFS to split the input characters.

    console
    $ input="Hello:World:This:Works"; IFS=':' read -r -a del_array <<< "$input"
    
  4. Print all elements in the array.

    console
    $ echo "${del_array[@]}"
    

    Output:

    Hello World This Works

Validate User Input Using the Read Command and Conditional Statements in Bash

The read command captures and assigns user inputs to variables. You can use these variables to perform specific tasks like validating user input using conditional statements by following the steps below.

  1. Create a new validate.sh script.

    console
    $ nano validate.sh
    
  2. Add the following contents to the validate.sh file.

    bash
    #!/bin/bash
    
    admins=("user1" "user2" "user3")
    
    read -p "Enter your username: " name
    
    if [[ " ${admins[@]} " =~ " $name " ]]; then
        echo "You have sudo user privileges!"
    else
        echo "Access denied, you don't have sudo user privileges"
    fi
    

    Save and close the file.

    The above script compares the user input from the name variable using the if-else conditional statement. If the condition returns true and the name matches any element in the admins array, the script executes the following commands.

  3. Run the script using Bash.

    console
    $ bash validate.sh
    

    Enter a valid user, such as user1 when prompted.

    Enter your username:

    Output:

    You have sudo user privileges!

Conclusion

You have used the bash read command to capture and validate user input. You have also combined the read command with loops, conditional expressions, and arrays to perform specific tasks. The read command is important when automating Bash scripts that require user input to perform specific actions on a system.