Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 28 Oct 2010 08:11:48 -0700
From:      Chip Camden <sterling@camdensoftware.com>
To:        FreeBSD Questions <freebsd-questions@freebsd.org>
Subject:   Re: [OT] writing filters in sh
Message-ID:  <20101028151148.GB73337@libertas.local.camdensoftware.com>
In-Reply-To: <20101027212841.GA67716@guilt.hydra>

index | next in thread | previous in thread | raw e-mail

[-- Attachment #1 --]
Quoth Chad Perrin on Wednesday, 27 October 2010:
> I know that in sh you can get the contents out of files specified as
> command line arguments:
> 
>     while read data; do
>       echo $data
>     done <$@
> 
> I know you can also get the contents of files from pipes and redirects:
> 
>     while read data; do
>       echo $data
>     done
> 
> In Perl, you can use a single construct to do both and, unlike the first
> sh example, it can also take multiple filenames as arguments and
> effectively concatenate their contents:
> 
>     while (<>) {
>       print $_;
>     }
> 
> I'm not exactly an *expert* in sh, in part because when things start
> getting "interesting" while I'm writing shell scripts I tend to just use
> a more robust language like Perl.  Please let me know if there's some way
> to use a simple idiom like the Perl example to get the same results in
> sh.
> 
> -- 
> Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ]


Here's a way to do what you're wanting to do.  Unfortunately, it isn't a
generalized, single construct:

#!/bin/sh
if [ $# -ge 1 ];then
  exec cat $@ | $0
  exit
fi

while read data; do
  echo $data
done

My lame attempts to generalize the first paragraph into an alias,
function, or shell script have met with disappointment.

-- 
Sterling (Chip) Camden    | sterling@camdensoftware.com | 2048D/3A978E4F
http://camdensoftware.com | http://chipstips.com        | http://chipsquips.com

[-- Attachment #2 --]
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (FreeBSD)

iQEcBAEBAgAGBQJMyZK0AAoJEIpckszW26+Rd/AIAKpDWnVpP+SDncbG0ClSdY8v
47Cr0QTZxEVuO4TaXkTLXrW+VtHXwYA13XLGfRaDiS5ocQzHRkV4UL3ffQXRR+5b
XtjfirVAJissoW9wgKaw+7YxjVlRVv1+Qx8enRUBx3tRIFZG4fIdY6XRuIf5dHBz
Npr8X64W8ymljd/65q04pMB3jdqC9Ui6kl3w7cWt1BsU/ECiLfFW0AGfCxpikGWt
HbdtfNO2ydJnvTpJA2fpG7J48PxoDk8HFLs1XCEOCnuWg35TvcT3Razv8Awj79tA
X5UAKSZ2sXjcArgEkVZN6DOURVRJmx1tb5jC4N5cwiUmMNRBbBZ7JmAibL+RXyI=
=O6v7
-----END PGP SIGNATURE-----
home | help

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