When to use read
Use read to assign input to shell variables while controlling whitespace and backslash interpretation. Input comes from the process's standard input, so interactive use and reading from a file have different blocking behavior.
Syntax
read [PARAMETERS] [VARIABLE...]Square brackets mark optional arguments; an ellipsis means repetition. Replace example file names, user names and server addresses with your own values.
Common options and arguments
Usage examples
Read a string preserving spaces
IFS= read -r answerOne line is read without trimming through IFS or interpreting backslash escapes.
Request a name in Bash
read -r -p 'Project name: ' projectAn interactive prompt requests a project name and stores the answer.
Read a line from a file
IFS= read -r first_line < ./notes.txtThe first line of a file is assigned in the current shell through input redirection.
Notes and limitations
- This is a shell builtin command; examples with -p and -s refer to Bash.
- Reading in a subshell or some pipelines does not save the variable in the parent shell.
Common questions and troubleshooting
Why does read appear to hang?
It may be waiting for a line from the terminal or another open input stream. Verify the intended input source and whether a timeout is appropriate.
Why is a value lost after a pipeline?
Some shells execute pipeline components in subshells. Use redirection or the shell's supported pattern when the variable must remain in the current shell.
Further help
Options vary by version and distribution. Check the installed documentation with this command: help read.