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 mensajeShows the message before reading.
-sSilent mode: does not echo what is typed, useful for passwords.
-rTreats backslashes as normal text.
-n NFinishes after reading N characters, without waiting for Enter.
-t segundosGives up if there is no answer in that time.
-a arrayStores the words read in an array.
-d carácterUses that character as the end of input instead of a newline.
Usage examples
read -p "Nombre: " nombreAsks for a name and stores it in the nombre variable.
read -s -p "Contraseña: " claveAsks for a password without showing it on screen.
read -t 5 -p "¿Continuar? [s/n] " respWaits for the answer for 5 seconds at most.
while read -r linea; do echo "$linea"; done < datos.txtWalks 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.