zero-trip foreach loops

Chris Torek chris at umcp-cs.UUCP
Wed Oct 8 15:47:03 AEST 1986


In article <2494 at utai.UUCP> lamy at utai.UUCP (Jean-Francois Lamy) writes:
>Is there an easy way to have csh foreach loops that don't complain if the
>pattern given does not match any file, as may occur in the inner loop of this
>bit of code:
>
>    set fontname = `basename $font .tfm`
>    foreach size ($fontname.*pxl)
>    ...
>    end

The problem is not foreach, but *.

    foreach foo ()
	echo $foo
    end

works fine.

The C shell's globber can be made to behave much like the Bourne
shell's by setting the variable `nonomatch':

    set nonomatch
    foreach size ($fontname.*pxl)
    ...

This is not really ideal, as a lack of matches will then cause
the loop to run once, with `size' set to, e.g., `amtex10.*pxl'.

>I've tried 
>    foreach size (`ls -1 $fontname.*pxl`).  
>This stops the script from aborting, but still gives me the stupid
>'No match' message.

If you `set nonomatch', this will not complain about `no match';
however, `ls' will complain `amtex10.*pxl not found'.

Personally, I would stick to `sh', and add a check for `no match':

for font in *.tfm; do
	fontname=`basename $font .tfm`
	for size in $fontname.*pxl; do
		case $size in
		"$fontname.*pxl") ;;	# ignore `no match' name
		*)	...
		esac
	done
done
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 1516)
UUCP:	seismo!umcp-cs!chris
CSNet:	chris at umcp-cs		ARPA:	chris at mimsy.umd.edu



More information about the Comp.unix mailing list