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



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".

-- 
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'



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