Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Why does the following code always outputs "0"?

#!/bin/bash

RETVAL=0
echo -e '1\n2' | while read number; do
    RETVAL=1
done

echo $RETVAL
share|improve this question
2  
    
fvue.nl/wiki/… –  Zoredache Oct 9 '12 at 15:37

2 Answers 2

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

 
discard

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.