[OT] writing filters in sh

Chip Camden sterling at camdensoftware.com
Thu Oct 28 15:11:54 UTC 2010


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 at camdensoftware.com | 2048D/3A978E4F
http://camdensoftware.com | http://chipstips.com        | http://chipsquips.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 488 bytes
Desc: not available
Url : http://lists.freebsd.org/pipermail/freebsd-questions/attachments/20101028/e822cb30/attachment.pgp


More information about the freebsd-questions mailing list