3

So I have some setup scripts at work, which only work with bash (because they use e.g. == or $BASH_SOURCE).

It works to source these scripts using zsh's emulate command:

emulate bash
source setupscipt.bash
emulate zsh

But this resets my zsh opts like "autocd" (set in .zshrc).

How should I start and quit emulation of bash, so that my opts stay as they are?

3

Zefram answered a similar question on the zsh mailing list over 20 years ago:

The solution is to use a function -- let's call it source_bash -- to source you bash script:

function source_bash {
  emulate -L bash
  builtin source "$@"
}

The trick is the option localoptions (set by the -L parameter of the emulate call), which is described as follows in the man page:

LOCAL_OPTIONS If this option is set at the point of return from a shell function, most options (including this one) which were in force upon entry to the function are restored; options that are not restored are PRIVILEGED and RESTRICTED. Otherwise, only this option, and the LOCAL_LOOPS, XTRACE and PRINT_EXIT_VALUE options are restored. Hence if this is explicitly unset by a shell function the other options in force at the point of return will remain so. A shell function can also guarantee itself a known shell configuration with a formulation like `emulate -L zsh'; the -L activates LOCAL_OPTIONS.

Put this function to your ~/.zshrcand you'll only need to do a

$ source_bash setupscipt.bash

when necessary.

  • Cool trick, but just to be shure: Environment variables which are set in the setupscript will then also be set in the parenting zsh? – Jounathaen Mar 23 '18 at 18:50
  • 2
    @Jounathaen: Yes. The localoptions option only restores the zsh options; the environment keeps unchanged. But please try, if it's working for your setup exactly as you want it. – mpy Mar 23 '18 at 18:59
  • 1
    As mentioned in the last line of that man page quote, one can use the shorter emulate -L bash instead of having setopt localoptions on its own line. :) – ZeroKnight Mar 25 '18 at 3:47
  • @ZeroKnight: Yes, you're right. I edited the function accordingly. – mpy Mar 25 '18 at 8:12

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.