Scripting
8 minwhile read, and the pipe that eats your variable
Every stage of a pipeline is a subshell.
Every stage of a pipeline runs in a subshell — a copy of the shell that is thrown away when the pipeline ends. Anything a stage assigns is assigned in that copy.
So echo x | read var sets var in a shell that no longer exists, and nothing reports an error. It is the most reliable surprise in the language.
Try this
The fix is to move the pipe, not the read. A redirection keeps the loop in this shell.
The same applies to a while read loop: redirect the file into the loop rather than piping it in, and the variables survive.
read -r is almost always what you want: without it, a backslash in the input is treated as an escape.
Try this
$
Files
| Mode | Links | Size | Name |
|---|---|---|---|
| -rw-r--r-- | 1 | 36 | words.txt |