Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux shell bug? Variable assignment in pipe does not work

Tags:

linux

shell

How come FILE_FOUND is 0 at the end of this bugger :

FILE_FOUND=0

touch /tmp/$$.txt

ls -1 /tmp/$$.* 2>/dev/null | while read item; do
    FILE_FOUND=1
    echo "FILE_FOUND = $FILE_FOUND"
done

echo "FILE_FOUND = $FILE_FOUND"

rm -f /tmp/$$.txt 2>/dev/null

??!!

On Unix FILE_FOUND stays at 1 (as it should), but on Linux (RedHat, Cygwin, ..) it jumps back to 0!!

Is it a Linux shell feature, not a bug? :)

Please help.

like image 456
ExpertNoob1 Avatar asked Sep 14 '26 23:09

ExpertNoob1


1 Answers

common issue which is caused because you're piping into the while, which is therefore run in a subshell, which can't pass environment variables back to its parent. I'm guessing that "unix" is different in this regard as you're running a different shell there (ksh?)

piping to the while loop may not be required. could you use this idiom instead?

for item in /tmp/$$.*; do
    ....
done

If you must use a subshell, then you'll have to do something external to the processes like:

touch /tmp/file_found
like image 103
pixelbeat Avatar answered Sep 16 '26 15:09

pixelbeat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!