Counter in sh inside loop, value "encapsulation"

Polytropon freebsd at edvax.de
Wed Dec 4 17:13:10 UTC 2019


In a sh script, I have a counter inside an interator.
The iterator is fed by piping with some greo output.
It looks like this:

#!/bin/sh
# ...
# ... lots of boring stuff omitted ...
# ...
echo "Start: ${TIMESTAMP}"
echo "Input: ${INFILE} (${TOTAL} entries, ${SKIPPED} skipped, ${REMAINING} remaining)"
COUNT=0
grep "^https" ${INFILE} | while read URL; do
	COUNT=`expr ${COUNT} + 1`
	echo
	echo "     ${COUNT} / ${REMAINING}"
	echo "---> ${URL}"
	# ...
	# ... processing per URL, also boring ...
	# ...
done
echo
echo "URLs processed: ${COUNT}" # <--- (!) THIS IS ZERO!
echo -n "Time: ${TIMESTAMP} - "
date "+%Y-%m-%d %H%:%M:%S"
echo ""
exit 0

So while the loop runs, the counter is increased for
each URL which is processed. After leaving the loop,
$COUNT is zero, for example:

	Input: bla.txt (20 entries, 15 skipped, 5 ermaining)
	1 / 5
	2 / 5
	3 / 5
	4 / 5
	5 / 5
	URLs processed: 0

The correct response should be: "URLs processed: 5".

Obviously, I fail to understand something important,
and that is not an acceptable option. :-)

I assume this is some problem due to subshell calling,
maybe because of "grep | while". If I set COUNT=100
before the loop, it'll be 100 after it finishes.

How can I have the final value of $COUNT _outside_ the
loop for the final status message? Note that $COUNT
will receive error checking, so it won't end at the
same value as $REMAINING if something goes wrong, i. e.,
the +1 won't happen if the processing step does not
successfully terminate and leave a $? -eq 0. But I
won't add that check unless I can get the correct
value at the end... :-)


-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...


More information about the freebsd-questions mailing list