Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 4 Dec 2019 18:13:00 +0100
From:      Polytropon <freebsd@edvax.de>
To:        FreeBSD Questions <freebsd-questions@freebsd.org>
Subject:   Counter in sh inside loop, value "encapsulation"
Message-ID:  <20191204181300.8dd0e03c.freebsd@edvax.de>

next in thread | raw e-mail | index | archive | help
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, ...



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20191204181300.8dd0e03c.freebsd>