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

Re: N=5 echo $[N-1] why doesn't it work as expected

2009/7/17 Peter Stephenson <pws@xxxxxxx>:
> On Fri, 17 Jul 2009 09:39:15 +0200
> Miek Gieben <miek@xxxxxxx> wrote:
>> [ Quoting Helmut Jarausch in "N=5 echo $[N-1] why doesn't it work"... ]
>> > Hi,
>> >
>> > sorry for this very simple question.
>> >
>> > N=2
>> > N=5 echo $[N-1]
>> > displays 1 - I'd expected 4.
>> > Would anybody please explain why?
>> $N is evaluated first, so it says:
>> N=5 echo $[2-1]
> Kind of.  More precisely, the command line "echo $[N-1]" undergoes
> expansion ending up with "echo 1".  At this point, if this was an external
> command, a fork would take place and N=5 would be put permanently into the
> background of the exec'd command---this is the point of the that notation,
> for use inside the guts of the command being executed.  In this case it's a
> shell internal command, so there's no fork, but the shell mimics the
> behaviour with external commands by exporting the value before executing
> the command, and then removing it afterwards.  In both cases it's too late
> to affect expansion.  (So you get the same result with /bin/echo as with
> echo.)
> You can force the expansion to take place later with a function:
> % fn() { echo $((N-1)) }
> % N=5 fn
> 4
> This illustrates what I meant by the value in the environment being "for
> use inside the guts of the command being executed".

I thought of anonymous functions here and tried
N=5 () { echo $((N-1)) }
but I get no result, nothing is printed, and I don't seem to get a
function definition for any of "N", "N=5" or "5", and no error is
returned. It also seems to be illegal to put the expression in front
of a loop of some sort or a subshell or list, ie, N=5 for ... done,
N=5 { ... }, N=5 ( ... ), but at least those print "zsh: parse error
near `foo'".

If I'm not blind, it looks like zshparam(1) doesn't talk about this at
all and it's sort of hard to grep for; where is it documented?

Mikael Magnusson

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