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
Server Fault is a question and answer site for system and network administrators. It only takes a minute to sign up.
Sign up to join this communityWhy does the following code always outputs "0"?
#!/bin/bash
RETVAL=0
echo -e '1\n2' | while read number; do
RETVAL=1
done
echo $RETVAL
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
).
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.