Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "echo foo | read a ; echo $a" not working as expected?

Tags:

linux

shell

unix

I could replicate the problem with various shells under FreeBSD, GNU/Linux, and Solaris. It had me head-scratching for more than an hour, so I decided to post the question here.

like image 339
Diomidis Spinellis Avatar asked Dec 17 '08 14:12

Diomidis Spinellis


2 Answers

Due to the piping the read is executed in its own subshell.

echo foo | while read a; do echo $a; done

will do what you expect it to.

like image 85
Bombe Avatar answered Sep 30 '22 16:09

Bombe


alternative:

echo foo | (read a ; echo $a)

Edit:

If you need $a outside the subshell, you have to reverse the commands:

read a < <(echo foo); echo $a

this way the read is executed in the current process

like image 28
wimh Avatar answered Sep 30 '22 17:09

wimh