read one line with "read" in bash, but without "while"

Viewed 1753

I was trying to understand how "while read" works in bash, and i came accross a behaviour that i can't explain:

root@antec:/# var=old_value
root@antec:/# echo "new_value" | read var && echo $var
old_value
root@antec:/# 

It works fine with "while read":

root@antec:/# var=old_value
root@antec:/# echo "new_value" | while read var; do echo $var; done
new_value
root@antec:/# 

Can someone explain why it does not work when read is used without while ? Moreover, i don't understand how the value of "var" in the main shell can be seen from the allegedly subshell after the pipe ..

Thank you

4 Answers
Related