Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Strange behavior with "for i in .."



On Fri, 23 Sep 2011 13:29:49 +0300
Volodya Khomchak <kolombo.inc@xxxxxxxxx> wrote:
> I faced with strange behavior with "for i in ..".
> So the problem is next:
>    # for i in /etc/profile.d/*.sh;do echo $i;done
>    # zsh: bad math expression: operand expected at `/etc/profi...'
> But if I change "i" to "file" it would work:
>    # for file in /etc/profile.d/*.sh;do echo $file;done
>    # /etc/profile.d/1.sh
>    # /etc/profile.d/2.sh
> 
> zsh --version
> zsh 4.3.10 (x86_64)
> 
> So what is going on here ?

Probably the first time i is referred to in the shell was in something like

  for (( i = 0; i < stuff; i++ )); ...

or, in fact, any arithmetic involving "i".  This has caused "i" to be
implicitly typed as an integer.  This only happens if i doesn't exist at
that point.

There are various things you can do;

  typeset i

before you use i the first time will ensure it's a scalar (i.e. string)
value even if you use it in arithmetic subsequently.

Or,

  typeset +i i

before you use it for any other purpose than arithmetic.

Or, if the original use was in initialisation code and you don't want i
to be exposed by it, simply

  unset i

after that would be good enough.

Or, of course, you can keep i for integers and use another variable for
strings, which is in effect what you tried.

-- 
Peter Stephenson <pws@xxxxxxx>            Software Engineer
Tel: +44 (0)1223 692070                   Cambridge Silicon Radio Limited
Churchill House, Cambridge Business Park, Cowley Road, Cambridge, CB4 0WZ, UK


Member of the CSR plc group of companies. CSR plc registered in England and Wales, registered number 4187346, registered office Churchill House, Cambridge Business Park, Cowley Road, Cambridge, CB4 0WZ, United Kingdom
More information can be found at www.csr.com. Follow CSR on Twitter at http://twitter.com/CSR_PLC and read our blog at www.csr.com/blog



Messages sorted by: Reverse Date, Date, Thread, Author