Lazy environment variables

I was just thinking that it would be really useful if command-line shells supported lazy environment variables. Lately, because of my work on Scala I will often find myself entering a line something like

  2. export PATH=/home/linuxsoft/apps/java-ibm-1.5/bin:$PATH
  3. ...

This is, despite the write-once promises of Jave (well, JVM bytecode), Scala will fail to build or a test will fail on specific implementations of the Java runtime and VM. I have been doing this so frequently, I finally decided to write some ZSH shell scripts to make it a little less work.

Just having a short macro that does the above for all the various Java runtimes is not ideal, because then my

  1. PATH
keeps getting longer and longer. ZSH might be smart about this when caching lookups, but it is inelegant. Another solution is to write something that does a search and replace on my
  1. PATH
as a string. However, the most elegant solution would simply be to not perform expansion on the contents of
  1. PATH
until it must be passed as part of an exec

ZSH can do a lot, so maybe it already has some feature that approximates this, but it would be nice if I could just write something like

  2. lazy export PATH=$JAVA_BIN:$PATH
  3. export JAVA_BIN=/home/linuxsoft/apps/java-ibm-1.5/bin
  4. ...

And then my scripts can just operate on

rather than having to modify
  1. PATH

Update: I just noticed that setting the variable

is enough for most purposes, but the above concept still seems reasonable.


  1. Matt Hellige said,

    March 5, 2008 @ 3:52 pm

    export FOO=’$BAR/foo’
    export BAR=bar
    echo ${(e)FOO}

    That sort of does what you want. I have no idea if it’s really a good idea… Shells are really ridiculous little languages.

  2. washburn said,

    March 6, 2008 @ 11:01 am

    @Matt: That is a reasonable solution for most things, I’ll have to see if I can use it to simplify my .zshrc and .zshenv files. Unfortunately, it does not entirely solve the problem with special variables like PATH that you do not generally examine directly.

    The other issue is that in general this sort of thing is basically dynamic binding, so it might be nice to think about whether there is a better way to do things that would maintain lexical binding.

RSS feed for comments on this post · TrackBack URI

Leave a Comment