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

Re: Bug? in 'integer' behaviour

Phil Pennock wrote:
> In the distribution is Functions/randline which purports to show a
> random line from a file.  The problem seems to be caused by a variable
> declared integer not stripping off leading whitespace when assigned to.
> randline:
>  # get a random line from a file
>  integer z=$(wc -l <"$1")
>  sed -n $[RANDOM%z+1]p "$1"
> This produces a divide by zero error, as 'z' is always zero.  Removing
> the 'integer' keyword solves this, as does wrapping the RHS of the
> assignment in $[...].

I think it's the trailing characters after the number which are causing
the problem.  From wc you get something like
    128 .zshrc
and if you do

integer z="    128 .zshrc"

you get

zsh: bad math expression: illegal character: .

But I get that from the $[...] expression too.  I get the same
behaviour in ksh, except that there is an error message from the
$(...), so it looks standard.  As a workaround you could do:

integer z=${$(wc -l <"$1")%"$1"}

or in a more standard way

y=$(wc -l <"$1")
integer z=${y%"$1"}

Peter Stephenson <pws@xxxxxxxxxxxxxxxxx>       Tel: +39 050 844536
WWW:  http://www.ifh.de/~pws/
Gruppo Teorico, Dipartimento di Fisica
Piazza Torricelli 2, 56100 Pisa, Italy

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