Counter in sh inside loop, value "encapsulation"

Polytropon freebsd at edvax.de
Thu Dec 5 04:11:53 UTC 2019


On Wed, 4 Dec 2019 20:28:02 -0000 (UTC), Christian Weisgerber wrote:
> On 2019-12-04, Polytropon <freebsd at edvax.de> wrote:
> 
> > #!/bin/sh
> > COUNT=0
> > grep "^https" ${INFILE} | while read URL; do
> > 	COUNT=`expr ${COUNT} + 1`
> > done
> > echo "URLs processed: ${COUNT}" # <--- (!) THIS IS ZERO!
> 
> Each command of a pipeline is executed in a subshell.
> (Some shells, notably AT&T ksh, behave differently.)
> 
> This is the single most asked shell scripting question.

Okay, so exactly what I assumed - and what is probably buried
as basic knowledge in the backyard of my rotting brain. ;-)

Due to portability reasons, I can only use sh (and not bash).
There are other tools available like sed, awk, cut, paste, tee,
all the nice little standard tools you can expect everywhere.
I would now probably try to do something like this:

	grep ... | while ... do
		...
		echo "URLs processed: ${COUNT}"
	done | tee result.txt
	COUNT=`awk '<code>' result.txt`

The awk code will match the last of the "URLs processed:"
messages and return the value after the ":". That of course
is hardly an elegant solution, but will surely work. It
will probably be some /^.../ and END { printf(...) } magic
in there. :-)



On Wed, 4 Dec 2019 16:39:36 -0300, Mario Lobo wrote:
> Could you try that?
> 
> #!/usr/local/bin/bash
    ^^^^^^^^^^^^^^^^^^^

Sadly not. Due to portability reasons, and availability of
only the most fundamental UNIX tools on different platforms
where I don't have any kind of control to install bash, this
option is not possible. I also thought about getting rid of
the pipe as the main source of the "encapsulation problem",
which I would maybe try in a later revision of the script.
However this probably won't happen due to "never touch a
running system", "works on my machine", and "we don't have
time for that." ;-)





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


More information about the freebsd-questions mailing list