Carl works in research, and like most research organizations, half their code is carelessly glued together GUI tools, command line interfaces, and shell scripts. The other half, the half which does the real work, is Fortran. Sure, the code was written forty years ago, but the laws of physics haven’t changed, so it’s still good and it’s still fast.

Carl usually doesn’t have to touch the Fortran half. Instead, he usually looks at the other bit. Most things are run from shell scripts, and most of the work of the shell scripts is getting environment variables configured so that they Fotran code can actually run its model without having a heart attack.

So, for example, one of those environment variables is WORKINGDIR. WORKINGDIR holds a /very/long/path/to/a/deeply/nested/folder/someplace The Fortran model code also needs to know the location of the SYSDIR, which is always exactly two levels up from WORKINGDIR. No, the Fortran code can’t figure this out on its own, it’s too busy doing calculus. The shell script needs to figure it out.

The shell script which calculates it throws in a little wrinkle though: # calculate dir 2 levels up (Program doesn't allow .. in pathnames). So, no $WORKINGDIR/../.. here.

There are a number of ways one could solve this problem. The wrong way to solve this problem is this ksh script…

# calculate dir 2 levels up (Program doesn't allow .. in pathnames)
tmp=`echo $WORKINGDIR | tr -d /`
wctmp=`echo $tmp | wc -m`
wcwrk=`echo $WORKINGDIR | wc -m`
(( up2 = $wcwrk - $wctmp - 1 ))
export SYSDIR=`echo $WORKINGDIR | cut -d / -f 1-$up2 `

This code starts by using tr to strip out all the “/” characters. Then it counts how many characters are in the trimmed down version, and how many are in the original. The difference between these is the total number of directories in the path. Subtract another one from that. Then we use the cut command to grab from the 1st “/” character in the original path, up to the penultimate “/” character. Good news: this code is pretty confident $WORKINGDIR never ends in a slash, so this guarantees that we go up two levels.

Carl replaced this with the following one-liner: export SYSDIR=${WORKINGDIR%/*/*}, which accomplishes the exact same thing.

[Advertisement] ProGet supports your applications, Docker containers, and third-party packages, allowing you to enforce quality standards across all components. Download and see how!