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

Re: ksh compatibility: initial value of $_



On Fri, Mar 31, 2023 at 7:32 AM Jun. T <takimoto-j@xxxxxxxxxxxxxxxxx> wrote:
>
>     _    Initially,  the value of _ is an absolute pathname of the
>          shell or script being executed as passed in the environment.
>
> So zsh can just do the same thing?
> With the following patch, zsh behaves similarly with ksh?

With your patch:

% /bin/sh
$ Src/zsh -fc 'print $_'
/bin/sh
$ Src/zsh -fc 'echo $_'
print $_
$

Similar behavior from ksh, so it really is whatever happens to be in
the environment for '_' rather than an actual pathname.  This means
you only get the documented behavior when a new shell or script was
invoked via a previous shell that exports $_ appropriately (which
evidently zsh already does, though I can't immediately find the code).

% typeset -p _
typeset _=_
% printenv _
/bin/printenv
%

There's nothing in POSIX (that I can find) specifying any behavior of $_ at all.

One other notable difference (which I think has been mentioned before)
is demonstrated thus:

ksh93:
$ for _ in a b c; do echo $_; done
a
b
c
$ for _ in a b c; do echo X; echo $_; done
X
a
X
b
X
c
$

zsh (even with ARGV0=ksh):
% for _ in a b c; do echo $_; done

echo
echo
% for _ in a b c; do echo X; echo $_; done
X
X
X
X
X
X
%

So ... ksh assigns $_ only after each full complex command, and does
not otherwise treat it as special, whereas zsh assigns it after every
pipeline (and also after the "do" keyword, it seems) and cannot use it
as a normal parameter in between.  (This can be partly worked around
in a function body by using "local -h _" but then all special behavior
is lost.)

Incidentally, as far as I can tell from a quick bit of research, if
you want to compare zsh and ksh behavior it is not advisable to
install "ksh2020" (which is unfortunately the default "ksh" for Ubuntu
at least as of 20.04).  Explicitly install "ksh93" instead if you have
that option.




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