[Gllug] spaces and shell scripting

Peter Grandi pg_gllug at gllug.for.sabi.co.UK
Thu Sep 1 17:04:16 UTC 2005


>>> On Thu, 1 Sep 2005 15:45:04 +0100,
>>> pg_gllug at gllug.for.sabi.co.UK (Peter Grandi) said:

>>> On Thu, 01 Sep 2005 14:43:50 +0100, Jon Dye
>>> <jon at pecorous.co.uk> said:

jon> [ ... list files and then take different actions if the
jon> cardinality of the list is 0, 1 or >= 2 ... ]

pg_gllug> [ ... cleaner rewrite of two pass algorithm ... ]

As demonstrated earlier is no need to have a two pass algorithm,
because the first of two passes in effect infinite lookahead,
and one only needs 1-token lookahead in effect. However the
lookahead example is slightly involved, and a two pass method
might be enough...

As to a two pass methods, there are a couple of variants that
might be worthwhile:

* The first pass is only needed to see if the file list has
  length 0, 1 or >= 2; therefore the scan can be terminated
  soon, with 'head -2', giving this line to get the count:

   C="`find ${1+\"$@\"} -type f -print | head -2 | wc -l`"

  This may or may not save much (e.g. nothing if C is 0).

* Alternatively, one can, as some people suggested, store the
  whole file list returned in the ''lookeahead'' scan, obviously
  in a file (to put it inside a a shell variable is horrible).
  Revised script for this:

  #!/bin/sh

  ME="`basename \"$0\"`"

  doNoElements()	{ echo "$ME: no elements found"; }
  doSingleElement()	{ echo "$ME: single element '$1'"; }
  doOneOfManyElements()	{ echo "$ME: one of many elements '$1'"; }

  LIST="`mktemp`"; trap "rm -f '$LIST'" 0

  C="`find ${1+\"$@\"} -type f -print | tee \"$LIST\" | wc -l`"

  case "$C" in
  '0') doNoElements;;
  '1') : '1 file, scan again to get the name of that file'
       while read FILE; do doSingleElement "$FILE"; done;;
  *)   : 'N files, scan again to get the list'
       while read FILE; do doOneOfManyElements "$FILE"; done;;
  esac < "$LIST"

-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list