read
Read a line from stdin or a file into variables — options -r -p -s -t -n -a -d, IFS and looping over lines
read is a bash builtin: it reads one line from standard input, splits it into fields by $IFS and assigns them to variables. It's used to prompt the user, read a file line by line and parse delimited lines (/etc/passwd, CSV). Help — help read.
Syntax
read [options] [name…]
The first field goes into the first variable, the second into the second, and the whole rest of the line into the last one. Without names the whole line goes into the REPLY variable.
Options
| Option | What it does |
|---|---|
-r | don't process \: a backslash stays an ordinary character. Use it almost always |
-p 'text' | show a prompt before input — no newline, to stderr, and only if input comes from a terminal |
-s | don't echo typed characters — for passwords |
-t sec | wait no longer than the given time, fractions allowed (-t 0.5); on timeout the exit code is greater than 128 |
-n N | return after N characters without waiting for Enter (or earlier if a newline comes) |
-N N | read exactly N characters, ignoring newlines |
-a array | put the fields into array elements, starting at index 0 |
-d 'c' | read up to the character c instead of a newline; -d '' — up to a NUL byte |
-u fd | read from file descriptor fd instead of stdin |
-e | in a terminal use readline: arrow keys and Tab completion work |
-i 'text' | together with -e: prefill editable initial text |
IFS and field splitting
IFS holds the field separator characters; by default space, tab and newline.
| Form | What happens |
|---|---|
read a b | fields split by spaces; leading and trailing spaces are stripped; extra fields go into b |
IFS= read -r line | the whole line, without stripping spaces and without processing \ |
IFS=: read -r a b c | fields split by colon; IFS is changed only for this command |
IFS=, read -ra arr | fields split by comma — into an array |
Exit code
| Code | When |
|---|---|
0 | a line was read |
1 | end of file (EOF) — this is how while read loops end |
>128 | the -t timeout expired |
Examples
# ask for a name
read -rp 'What is your name? ' name
echo "Hello, $name"
# password without echo; -s prints no newline afterwards — add one with echo
read -rsp 'Password: ' pass; echo
# confirm with a single key
read -rn 1 -p 'Continue? [y/N] ' ans; echo
[[ $ans == [yY] ]] || exit 1
# an answer with a timeout and a default value
read -rt 5 -p 'Port [8080]: ' port || port=8080
# read a file line by line — the classic idiom
printf 'one\n two \nthree\n' > /tmp/lines.txt
while IFS= read -r line; do
echo "[$line]"
done < /tmp/lines.txt
# split fields by colon
while IFS=: read -r user _ uid _ _ home shell; do
echo "$user uid=$uid home=$home"
done < /etc/passwd
# a string into an array
IFS=, read -ra parts <<< 'red,green,blue'
echo "${#parts[@]} ${parts[1]}" # 3 green
# read a command's output and keep variables after the loop
count=0
while IFS= read -r f; do
count=$((count + 1))
done < <(find /etc -maxdepth 1 -name '*.conf')
echo "found: $count"
# file names with any characters: the delimiter is a NUL byte
find /tmp -maxdepth 1 -type f -print0 |
while IFS= read -r -d '' f; do echo "file: $f"; done
# all lines into an array at once — that's what mapfile is for
mapfile -t rows < /tmp/lines.txt
echo "${#rows[@]}"
Pitfalls
- Without
-rbackslashes disappear.read xturnsa\bintoab, and a\at the end of a line joins it with the next one. Writeread -r. - Without
IFS=spaces are stripped.read -r lineon the linetwogivestwo. To read a line exactly —IFS= read -r line. - A last line without
\nis lost.readreads it but returns 1, and thewhile readloop doesn't run its body. Guard:while IFS= read -r line || [[ -n $line ]]; do …. - A pipe into
whileis a subshell. Incmd | while read …; do n=$((n+1)); donethe variablenis unchanged after the loop. Feed input viadone < <(cmd)ordone < file, or enableshopt -s lastpipe(in a script). echo "a b" | read xsaves nothing for the same reason:readruns in a subshell. Useread x <<< "a b".- Commands inside the loop eat stdin.
ssh,ffmpegand other programs that read stdin will consume the remaining lines of the file. Give them< /dev/null(sshhas-n) or read the file through another descriptor:while read -r -u 3 line; do …; done 3< file. -p,-sand-eare meant for a terminal. If input comes from a pipe or a file, the-pprompt isn't printed and-schanges nothing —readjust reads the data.
See also
echo-printf · redirection · variables · conditions-loops · xargs