read

Linux · Terminal · reference only

What it does

Reads a line from standard input and stores it in one or more variables. It is used to ask the user for data in scripts.

Syntax

read [opciones] [variable...]

Options and parameters

  • -p mensaje

    Shows the message before reading.

  • -s

    Silent mode: does not echo what is typed, useful for passwords.

  • -r

    Treats backslashes as normal text.

  • -n N

    Finishes after reading N characters, without waiting for Enter.

  • -t segundos

    Gives up if there is no answer in that time.

  • -a array

    Stores the words read in an array.

  • -d carácter

    Uses that character as the end of input instead of a newline.

Usage examples

  • read -p "Nombre: " nombre

    Asks for a name and stores it in the nombre variable.

  • read -s -p "Contraseña: " clave

    Asks for a password without showing it on screen.

  • read -t 5 -p "¿Continuar? [s/n] " resp

    Waits for the answer for 5 seconds at most.

  • while read -r linea; do echo "$linea"; done < datos.txt

    Walks through a file line by line.

Notes and common mistakes

  • It is a bash builtin, not a separate program.
  • Use -r almost always to stop backslashes from being interpreted.

Related commands