Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Why does the following code always outputs "0"?


echo -e '1\n2' | while read number; do

echo $RETVAL
share|improve this question
3… – Zoredache Oct 9 '12 at 15:37

The while loop is part of a pipeline, and therefore runs in a subshell. Variables set in the subshell (RETVAL=1) don't affect the parent shell (echo $RETVAL).

share|improve this answer

It has to do with how the echo is not passing an EOF / Ctrl D to the while read.

If you pull the echo out and enter a Ctrl D to the while loop it will work as expected.

Not sure how to send a Ctrl D via an echo.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.