What it does
read NAME waits for a line and stores it in NAME. With more names, the words are split: the first word to the first name, the rest to the last one. With no name the line goes to $REPLY. while read -r LINE; do …; done < FILE is the standard way to process a file line by line.
How to write it
read [-ers] [-a ARRAY] [-d DELIM] [-i TEXT] [-n N] [-N N] [-p PROMPT] [-t TIMEOUT] [-u FD] [NAME]...Options 11
Most used
Nothing matches this filter.
Examples 10
$ run as a normal user# run as root (or with sudo)
1Ask a question
read -p "Your name: " NAME; echo "Hello $NAME"Simple input in scripts.
2Ask for a password
read -s -p "Password: " PASS; echoNothing is shown while typing.
3Process a file line by line
while read -r LINE; do echo "line: $LINE"; done < /etc/hostname-r keeps backslashes.
4Split fields
Words go to the names in order.
5Split /etc/passwd fields
IFS=: splits on colons.
6Yes/no with a timeout
Defaults to no after 10 seconds.
7Into an array
read -r -a PARTS <<< "a b c"; echo "${PARTS[1]}" bIndex starts at 0.
8Read command output (not a pipe into while)
Process substitution keeps variables after the loop.
9Default value with editing
read -e -i "/backup" -p "Target folder: " DIRThe user can edit the default.
10Pause a script
read -r -p "Press Enter to continue"Waits for Enter.
Nothing matches this filter.
Watch out
- Without -r, backslashes in the input disappear.
cmd | while read …runs the loop in a subshell: variables set inside are gone afterwards.
Exit codes
0 :: A line was read. 1 :: End of file (or timeout > 128 with -t).