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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With