title: A two-level symbolic link chasing function in Tcl
body: <p>The upshot of what I'm trying to do is write a <em>Tcl</em> function that is equivalent to the following shell:</p>
  
  <pre><code>get_real_home () {
      dirname $(ls -l $(ls -l $(which "$1") | awk '{print $NF}') | awk '{print $NF'})
  }
  </code></pre>
  
  <p>In short, this gives me the name of the directory that contains the actual binary that runs when I give it the name of a program managed by the <a href="https://wiki.debian.org/DebianAlternatives" rel="nofollow">Debian alternatives system</a> by following a symlink, usually in <code>/usr/bin</code>, to another symlink in <code>/etc/alternatives/</code>, which points at the executable (or whatever) of the alternative currently in use. For example:</p>
  
  <pre><code>$ get_real_home java
  /usr/lib/jvm/java-6-openjdk-amd64/jre/bin
  </code></pre>
  
  <p>The reason that I want to do this is that I am using <a href="http://modules.sourceforge.net/" rel="nofollow">Environment Modules</a>, whose “native language” is <em>Tcl</em>, to manage the environment settings (chiefly <code>PATH</code> and <code>LD_LIBRARY_PATH</code>) for a number of compilers, interpreters, and libraries. This utility is pretty well a <em>de facto</em> standard on clusters.</p>
  
  <p>For <em>Java</em> in particular (where there are many alternatives), it would be convenient to be able to set the environment (e.g. <code>JAVA_HOME</code>) to the right value for the current <em>Debian</em> alternative via an <em>Environment Modules</em> module that would “know” where the current <em>Debian</em> alternative points at. For that, the above symlink chaser is handy.</p>
  
  <p>Of course, I <em>could</em> just stick what I already have (above) into a shell script and call that from <em>Tcl</em> in <em>Environment Modules</em>: a pragmatic if inelegant solution. I'd prefer the better “native” <em>Tcl</em> solution, but owing to my total ignorance of <em>Tcl</em>, I'm having difficulty doing it, despite it seeming like it should be trivial.</p>
  
  <p>I'm sure this <em>is</em> trivial to someone who knows <em>Tcl</em>, but that isn't me :(</p>