The read command in Linux: reading user input in scripts

Introduction

In shell script task automation, it is often necessary to interact with the user to request data, confirm actions, or receive specific configurations. The Bash read command allows capturing standard input from the keyboard and storing it in variables, making scripts much more flexible and user-friendly. In this article we will explore its syntax, the most useful options, and several practical examples that you can apply immediately in your own scripts.

Basic syntax

The simplest form of read is: read variable. This command pauses script execution and waits for the user to type a line of text, ending with the Enter key. What is entered is stored in the indicated variable. If no variable is specified, the content is stored in the special variable REPLY. Additionally, read accepts several flags that modify its behavior, such as -p to display a prompt, -s to hide input (useful for passwords), -t to set a timeout, -n to limit the number of characters, -r to prevent the backslash from acting as an escape character, and -a to read directly into an array.

Most used options

  • -p ‘texto’: shows the text as a prompt message before reading input.
  • -s: silent mode, does not show what the user types (ideal for passwords).
  • -t seconds: sets a timeout; if exceeded, read terminates with an error code.
  • -n number: limits reading to that number of characters; after reaching them, read returns automatically.
  • -r: backslash does not act as an escape character, it is read literally.
  • -a nombre_array: stores each word read in an element of the indicated array.

Practical examples

Simple read with prompt

#!/bin/bash
read -p 'Enter your name: ' nombre
echo Hello, $nombre!

Password read

#!/bin/bash
read -s -p 'Enter your password: ' password
echo
echo 'Password stored (in a real case it would have to be hashed).'

Read with timeout

#!/bin/bash
if read -t 5 -p 'Continue? (y/n): ' respuesta; then
    echo Response: $respuesta
else
    echo Timeout, assuming 'n'.
    respuesta=n
fi

Read into an array

#!/bin/bash
read -a frutas -p 'Enter three fruits separated by spaces: '
echo You have chosen: ${frutas[0]}, ${frutas[1]} and ${frutas[2]}

Process a file line by line

#!/bin/bash
while IFS= read -r linea; do
    echo Line read: $linea
done < archivo.txt

Error handling and validation

It is important to check the exit code of read to detect situations such as timeout exhausted or interruption via Ctrl+D. The special variable $? contains the status of the last command; a non-zero value indicates a failure. Additionally, after reading you can validate the content using regular expressions or simple comparisons:

  • if [[ -z $variable ]]; then echo ‘Empty input’; fi
  • if ! [[ $variable =~ ^[0-9]+$ ]]; then echo ‘Not a number’; fi

Combining the -t option with a test of $? allows offering a default value when the user does not respond in time.

Best practices

  • Always use -r unless you need the backslash to function as an escape.
  • Enclose variables in double quotes when using them to avoid problems with spaces or special characters.
  • When requesting sensitive information, combine -s with -p and, after using the data, delete the variable if it is not necessary to keep it (unset variable).
  • For readings that come from files, combine IFS= and -r to preserve leading and trailing spaces.
  • Document the purpose of each read within the script with clear comments.

Conclusion

The read command is an essential tool for creating interactive and adaptable scripts in Linux. Mastering its syntax and options allows you to request data securely, control timeouts, store inputs in arrays, and handle errors appropriately. Applying the good practices described, your scripts will be more professional, secure, and easy to use for both you and other users.

This post is also available in ESPAÑOL.

Leave a Reply

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

Esta obra está bajo una Licencia Creative Commons Atribución 4.0 Internacional para Francesc Roig francesc@vivaldi.net .