Read command and user inputs

The read command in Linux is a shell built-in that allows you to read a line of input from the terminal. It is often used in shell scripts to prompt the user for input or to read input from a file or pipe.

Here is the basic syntax for the read command:

read [options] VARIABLE

The read command reads a single line of input and stores it in the specified VARIABLE. The line of input is terminated by a newline character.

Here is an example of using the read command to prompt the user for their name:

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

This script will print “Enter your name: ” and then wait for the user to enter their name. The name that the user enters is stored in the name variable, and then the script prints “Hello, [name]” with the user’s name.

The read command has a number of options that can be used to control its behavior. For example, the -p option allows you to specify a prompt string, and the -t option allows you to specify a timeout for the command. You can use the -d option to specify a delimiter other than a newline, and the -a option allows you to read the input into an array.

Option Description
-a Read the input into an indexed array instead of a single variable.
-d Specify a delimiter character other than a newline to terminate the input.
-p Specify a prompt string to be displayed before reading the input.
-r Do not treat backslashes as escape characters.
-s Do not echo the input to the terminal.
-t Specify a timeout in seconds to wait for input.
If no input is received within the timeout, the command will exit.
-u Read input from the specified file descriptor
(e.g. -u 3 reads from file descriptor 3).

Here are some examples of using the read command in Linux:

  • Prompt the user for their name and store it in a variable:
    echo "Enter your name: "
    read name

    echo "Hello, $name"
  • Read a list of names from a file and store them in an array:
    # Assume the file "names.txt" contains a list of names, one per line
    read -a names < names.txt
    echo "The names are: ${names[@]}"
  • Read input from a pipe:
    # Assume the command "generate_input" generates a stream of input
    generate_input | while read line; do
       echo "Received: $line"
    done
  • Read input from the terminal with a timeout of 5 seconds:
    echo "Enter your name (5 seconds): "
    read -t 5 name if [ -z "$name" ];

    then
       echo "Timed out!"
    else
       echo "Hello, $name"
    fi
  • Read input from the terminal without echoing it to the screen:
    echo <span class="hljs-string"
    -s password
    <span class="hljs-built_in"

For more information on the read command and its options, you can consult the man pages or run help read at the command prompt.

License

Developers ultimate guide: Linux Bash scripting Copyright © 2022 by Matin Maleki. All Rights Reserved.

Share This Book