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

Re: 'emulate sh -c' and $0



On 2014-06-03 17:10, Bart Schaefer wrote:
> On Jun 3, 2014 1:27 PM, "Peter Stephenson" <p.w.stephenson@xxxxxxxxxxxx>
> wrote:
>> On Tue, 03 Jun 2014 16:15:25 -0400
>> Richard Hansen <rhansen@xxxxxxx> wrote:
>>> Although it would be a behavior change, I think it would be best if both
>>> 'emulate sh' and 'emulate sh -c' set POSIX_ARGZERO by default
>>
>> Yes, that's the policy --- backward compatibility is for native mode, sh
>> compatibility can be improved without worrying about that.
> 
> The complexity here is that we're not just dealing with a particular
> emulation, we're dealing with switching from one emulation to another (and
> possibly back again) in the middle of a running shell session, and the
> effect that has on a dynamically scoped variable that crosses the emulation
> boundaries.

Isn't this a general problem with how zsh supports mix-and-match shell
code?  Here's a contrived example:

    echo_stuff() { printf %s\\n "$*"; }
    foo() { ${CMD} words here; }
    CMD=echo_stuff
    IFS=_
    printf "outside sh emulation: "; foo
    printf "inside sh emulation:  "; emulate sh -c foo

As stated in detail #2 in the documentation for the emulate builtin,
options aren't restored when calling foo from sh emulation mode.  That
causes the above script to produce the following output:

    outside sh emulation: words_here
    inside sh emulation:  stuff words here

Because foo was defined outside of emulate I would have expected zsh to
treat the body of foo as native zsh code regardless of the emulation
mode of the calling code.  If I hadn't read the detailed emulate rules
and didn't understand how emulate worked with regard to options, I would
have expected the following output:

    outside sh emulation: words_here
    inside sh emulation:  words_here

(same output for the same function in the same script)

To get the behavior I expect, I have to do the following:

    define_functions() {
        echo_stuff() { printf %s\\n "$*"; }
        foo() { ${CMD} words here; }
    }
    emulate zsh -c define_functions
    CMD=echo_stuff
    IFS=_
    printf "outside sh emulation: "; foo
    printf "inside sh emulation:  "; emulate sh -c foo

If zsh restored options when a non-sticky function is called from within
emulation then I wouldn't have to do the above define_functions hack.
(And $0 would act like I expect assuming POSIX_ARGZERO is enabled in sh
emulation mode.)

-Richard



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