Why can't I read fill variables when used at the end of the pipe?

Why is the conclusion empty?

echo "abcd" | read XYZV echo $X 

I thought it would be a .

+4
source share
3 answers

The problem is that to run the read command with its input redirected from echo , a new subshell process is created. This process reads the values, assigns them to the variables - and then exits; then the second echo command is executed. To demonstrate this, you can make a second echo and read as from a subshell:

 $ echo "abcd" | ( read XYZV; echo $X ) a 
+6
source

In Bash, you can do several different things to accomplish this:

A here is the line:

 read XYZV <<< $(echo "abcd"); echo $X 

Process Replacement:

 read XYZV < <(echo "abcd"); echo $X 

And here is a command substitution document:

 read XYZV <<EOF $(echo "abcd") EOF echo $X 

This document method will also work with POSIX shells in addition to Bash.

If you are reading from a file and not from the output of another command, this is a little easier.

+6
source

I believe this is because echo "abcd" | read XYZV echo "abcd" | read XYZV and echo $X are separate statements (I'm not sure about the exact expression)? Therefore, no one knows about anything else.

EDIT: Give echo "abcd" | ( read XYZV; echo $X ) echo "abcd" | ( read XYZV; echo $X ) try ...

+5
source

Source: https://habr.com/ru/post/1310046/


All Articles