I have 2 different scripts doing basically the same: counting the subdirectories in the current directory:
c=0
ls -l | grep "^d" | while read zeile
do
c=`expr $c + 1`
echo $c
done
echo "Subdirs: $c"
and
c=0
while read zeile
do
c=`expr $c + 1`
echo $c
done < <(ls -l | grep "^d")
echo "Subdirs: $c"
My Problem is, that in the first version, “c” seems to lose it’s value after the while-loop has finished.
The outputs
1)
1
2
3
Subdirs: 0
2)
1
2
3
Subdirs: 3
Can anyone of you explain to me, why this is happening?
Thanks in advance
Alex
In the first case, the assignment to c happens after the
|, i.e. in a subshell. You cannot change a variable in a parent shell from a subshell.BTW, why do not you use
let c++instead of backquotes and expr?