0

These are the commands:

$ echo $LINE

$ echo TEXT
TEXT
$ echo TEXT | read LINE
$ echo $LINE

$ 

I would expect "echo "$LINE" to return "TEXT", but its empty. Any ideas?

  • 1
    This looks like a near-duplicate of ["Bash variable scope"](https://stackoverflow.com/questions/124167), ["variable reset in a bash script"](https://stackoverflow.com/questions/8086376), ["Variables empty after inner loop"](https://stackoverflow.com/questions/19655013), ["Why does my Bash counter reset after while loop"](https://stackoverflow.com/questions/5006229), and many others. See [BashFAQ #24: "I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?"](http://mywiki.wooledge.org/BashFAQ/024) – Gordon Davisson Nov 10 '21 at 05:54

1 Answers1

2

Pipes create a subshell, and a variable created in a subshell does not exist in the main environment.

You can do:

$ read line < <(echo 'my text')
$ echo "$line"
my text
dan
  • 4,846
  • 6
  • 15