Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weird behaviour with nested loops in bash

I'd like to know why this bash script

#!/bin/bash
seq 1 3 > foo
COUNT=0
while read VAR1; do
    while read VAR2; do
        let COUNT++
        echo -n $COUNT
    done < foo
done < foo

outputs: 123456789

while this other bash script, that (AFAIK) should do the exact same thing

#!/bin/bash

seq 1 3 > foo

COUNT=0
while read VAR1; do
    cat foo | while read VAR2; do
        let COUNT++
        echo $COUNT
    done
done < foo

outputs: 123123123

like image 436
blue Avatar asked Jan 13 '23 06:01

blue


2 Answers

The difference is that the pipeline runs in a subshell. Therefore, changes to the COUNT variable do not persist after the end of the inner loop in the second case.

like image 112
choroba Avatar answered Jan 22 '23 05:01

choroba


Using | invoke a subshell and hence your variable holds no value in it.

A quick look at the debug log will explain the scenario. Run both script as bash -x scriptname and you should answer yourself.

like image 21
jaypal singh Avatar answered Jan 22 '23 07:01

jaypal singh