echo hello | read name #no work

Doyan

n00b
Joined
Nov 9, 2006
Messages
18
Hi, I am stumped as to why the follow command does not work.

Code:
echo hello | read name

I have tried the command on a couple different linux distro's and it does not save the word hello in the name variable. Odd thing is it doesn't return a error either, it returns the prompt which leads me to believe it worked but when I echo the variable $name, nothing is saved in it.
 
The problem is that when you use a pipe the read command is being executed in a subshell, so you can't access the variable locally. As to how to get around that...my shell scripting skills are rather lacking. >.>
 
Since people have been posting "better" ways todo this (and they are right) I thought I would just post how todo what you want (if you /really/ want todo it that way...)

read, reads from stdin, thus you must pass it data from stdin. a PIPE is NOT!!! stdin

Code:
read name < <(echo hello)
echo $name
 
Back
Top