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

Re: autoload variables

On Mon, Aug 30, 2021 at 5:23 PM Anthony Fletcher <anthony@xxxxxxxx> wrote:
> We can autoload functions but is there a way to autoload variables?
> My .zshenv and .zshrc files are getting longer and slower with more lists of exported variables that are useful but only needed in a few sessions. For instance, one variable is to identify the default uplink interface
>    export UPIF=$(ip -4 r | sed -n -e '/^default/ s/^default.*dev //; s/ .*// p;q' )
> Useful when I'm debugging the network but not needed otherwise.
> Can I autoload these variables as needed?

Zsh doesn't know which commands respect UPIF environment variable, so
if it supported autoloadable environment variables it would have to
autoload all of them when you run the first command. Hardly an
improvement over your current setup.

If you know which commands respect UPIF (I'll use foobar because I
don't know), you can try this:

  alias foobar='env UPIF=${UPIF-${UPIF::=$(ip -4 r | ...)}} foobar'

This will compute UPIF on the first invocation and remember the value
for the duration of the current zsh session.

This can be generalized so that you could do this in zshrc:

  # Define how UPIF and BLAH environment variables are computed.
  function lazy-env-UPIF() ip -4 r | sed ...
  function lazy-env-BLAH() print 42

  # Declare that foobar command needs UPIF and BLAH environment variables.
  cmd-needs-env foobar UPIF BLAH


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