Skip to content
Advertisement

Parsing parameters with zparseopts, but from within a sourced script

I have a zsh script myscr.zsh, which sources another script zparse.zsh, like this:

#!/usr/bin/zsh
# This is mysrc.zsh
. $HOME/slib/zparse.zsh FOO BAR # some parameters passed to zparse.zsh

zparse.zsh expects a variable number of parameters, which do NOT need to be parsed using zparseopt, but zparse.zsh should – among other things – parse the positional parameters passed to mysrc.zsh. This is tricky, since mysrc.zsh has its own copy of $, which is different from the $ within zparse.zsh.

To make things even more difficult, zparseopt does by design always parse $*; we can’t tell it to use a different array.

I know that what I want is a bit like “having a cake and eating it too” – my zparse.zsh has its own parameter list, but also wants to process the parameter list of its parent.

My current, and not elegant, approach goes like this: I define a special, “magic” parameter (say: %), which is known to not occur within the parameter list given to zparse.zsh. I then invoke zparse.zsh like this:

. zparse.zsh FOO BAR % "$@"

Within zparse, I first shift the parameters until the magic parameter out of $* and into a local array, which leaves me with “$@” which is now identical to the one in the calling script, and use zparseopt on this.

I wonder whether there is a simpler solution. For example, can I somehow access the shell variables (and hence the $*) of the sourcing shell? I’m not talking about accessing the environment of the parent process, because we are in the same process here. Maybe zsh with all its goodies has some helpful feature, which I’m just unaware of?

Advertisement

Answer

you can copy the outer script’s $@ into another array and use that in zparse.zsh:

#!/usr/bin/zsh
outerargs=("$@")
. $HOME/slib/zparse.zsh FOO BAR

however, this is IMO appreciably worse than your current solution. in fact, i fail to see the alleged inelegance: zparse.zsh is explicit about values it works with (as opposed to the magician’s behind-the-back trick demonstrated in this answer) and there’s no ambiguity if you chose your separator well.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement