Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 5 Dec 2019 05:11:45 +0100
From:      Polytropon <freebsd@edvax.de>
To:        Christian Weisgerber <naddy@mips.inka.de>
Cc:        freebsd-questions@freebsd.org
Subject:   Re: Counter in sh inside loop, value "encapsulation"
Message-ID:  <20191205051145.78f9a805.freebsd@edvax.de>
In-Reply-To: <slrnqug5mi.srf.naddy@lorvorc.mips.inka.de>
References:  <20191204181300.8dd0e03c.freebsd@edvax.de> <slrnqug5mi.srf.naddy@lorvorc.mips.inka.de>

next in thread | previous in thread | raw e-mail | index | archive | help
On Wed, 4 Dec 2019 20:28:02 -0000 (UTC), Christian Weisgerber wrote:
> On 2019-12-04, Polytropon <freebsd@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, ...



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