Sync’ up! … without getting drained

feb 12

More Joy with CSH

There’s never a dull moment when scripting with CSH. Recently, I got the chance to revisit Bill Joy’s early CSH paper, and as expected, some little easter eggs emerged, some derp was revealed, and much joy was had.

The last time I read his paper, I found out about scratch files, and wrote about them on this very blog. I never did discover to what end these files were garbage collected every few days — my guess is Bill had some cronjob going through his systems removing files that started with ‘#’ but failed to mention that in his paper.

This time, I was reminded of a mechanism that can be used in conditionals — if statements, and whathaveyou — where an expression can be surrounded in ‘{}’ to capture its exit status. Usually, expressions just contain word-strings and you test them to see whether those words exist as files, dirs, etc. Or, perhaps, you just see whether your word-string stored as variable equals or matches some value you declare.

Of course, when I played around with the curly-braces, nothing seemed to act the way it was supposed to. Yes, it captured its status, but my very first attempt was failing in other strange ways only CSH can.

The following is what I was trying in my shell:

if( { ls -lhart > /dev/null } ) echo great

It says: check that my command exited as normal (0), and I don’t care about my output; echo ‘great’ if all went well.

And… Fail. I was seeing ‘great,’ but my redirect was not being honored: I was seeing my listings of ‘cwd.’

I threw my command into a sub-shell ‘()’ and tried that.

Success! Although my one-liner was beginning to look like Lisp, it worked and I made a note about this heuristic. After all, this was a pattern I expected to use more than a few times.

if( { ( ls -lhart >& /dev/null ) } ) echo great

For good measure, I added the ‘&’ to also redirect ‘stderr,’ or ‘Diagnostic Output’ as Bill Joy used to call it. That way, no matter how chatty my program was, it would be quiet, return a status that ‘{}’ would expand into the apt booleans, and all would be well.

Update Feb. 2023

Just when you thought it couldn’t get any more derpy, I discovered that whitespace is also important in fending off a major SNAFU.

It turns out that the command doesn’t like being too close to those curly braces, otherwise, nothing works. At least one tab/space has to pad your innner-most command for the forementioned pattern to work at all.