1

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
2

2 Answers 2

3

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).

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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