LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to define a variable In a while loop? (https://www.linuxquestions.org/questions/programming-9/how-to-define-a-variable-in-a-while-loop-500481/)

ntubski 03-02-2012 04:09 PM

export passes variables to subprocesses, but that doesn't help getting the data back to the parent:
Code:

$ export x=fish
$ echo $x
fish
$ whoami | while :;do x=chips;break;done
$ echo $x
fish

The problem is explained in detail here: I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?

hatalbot 07-30-2014 01:12 PM

Another way to fix the problem is to place the input into a file,
then redirection to have the while loop process the file

i.e.

-----------------------------------------------------------
Doesn't work due to pipe causing subprocess being created:
-----------------------------------------------------------
export conflict=0
cat $filename | while read inline
do
conflict=1
done

echo $conflict # get 0

--------------------
WORKS!
--------------------
export conflict=0
while read inline
do
conflict=1
done < $filename

echo $conflict # get 1 !

Since no pipe, no subprocess created, values in while loop retained


All times are GMT -5. The time now is 04:01 PM.