Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bizarre bash scoping rule eludes me

Tags:

bash

sum

Consider:

t=0 ; for i in 1 2 3 4 5 6 7 8 9 10 ; do t=$((t+i)) ; done ; echo $t

prints 55.

But:

totsize=0
find /home/user -type f -mmin -4860 -a -mmin +3420 | xargs du | \
while read size rest ; do
    totsize=$((totsize+size))
    echo "$totsize"
done
echo "Sum: $totsize kb"

Prints "Sum: 0 kb" even tho the interim print statement prints a reasonable sum.

I know I have encountered this issue before, but have never understood it. What is difference?

like image 213
Bittrance Avatar asked Dec 07 '22 22:12

Bittrance


1 Answers

totsize=0

while read size rest ; do
    totsize=$((totsize+size))
    echo "$totsize"
done < <(find /home/user -type f -mmin -4860 -a -mmin +3420 | xargs du)
echo "Sum: $totsize kb"

Prevent a subshell, because a subshell will limit the scope of totsize


Spending a few more words:

do_something < <(subprocess)
  • will run do_something in the main shell (this is input redirection with process substitution)

.

subprocess | do_something
  • will run do_something in a separate (sub) shell (this is a pipe subprocess)
like image 53
sehe Avatar answered Jan 01 '23 22:01

sehe