Counter in sh inside loop, value "encapsulation"
Mario Lobo
lobo at bsd.com.br
Wed Dec 4 19:41:09 UTC 2019
On Wed, Dec 4, 2019 at 2:13 PM Polytropon <freebsd at edvax.de> wrote:
> 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, ...
> _______________________________________________
> freebsd-questions at freebsd.org mailing list
> https://lists.freebsd.org/mailman/listinfo/freebsd-questions
> To unsubscribe, send any mail to "
> freebsd-questions-unsubscribe at freebsd.org"
>
Could you try that?
#!/usr/local/bin/bash
# ...
# ... lots of boring stuff omitted ...
# ...
echo "Start: ${TIMESTAMP}"
echo "Input: ${INFILE} (${TOTAL} entries, ${SKIPPED} skipped, ${REMAINING}
remaining)"
declare -a array=(`cat ${INFILE}`)
arraylength=${#array[@]}
COUNT=1
for (( i=1; i<${arraylength}; i++ ));
do
grep "^https" ${array[$i]}
echo
echo $COUNT"/"$arraylength
# echo "---> ${URL}"
# ...
# ... processing per URL, also boring ...
# ...
COUNT=$((COUNT+1))
done
echo
echo "URLs processed:" $COUNT
echo -n "Time: ${TIMESTAMP} - "
date "+%Y-%m-%d %H%:%M:%S"
echo ""
exit 0
--
Mario Lobo
http://www.mallavoodoo.com.br
FreeBSD since version 2.2.8 [not Pro-Audio.... YET!!]
More information about the freebsd-questions
mailing list