A note on shell coding conventions: Variables

Recently I talked in a dojo on the Bourne Shell and got asked what the naming conventions for shell variables were.

When I learned the shell (almost 30 years ago) AFAIR nobody cared about coding conventions very much, except for C and C++. So at the time, for reasons lost in the mist of history, I fell into the habit of writing shell variables in all caps, like MY_VARIABLE.

In the session this was the answer I gave to the question. I still think it's not a bad convention, because the variables tend to stick out from surrounding lowercase text:

echo "cannot open file $FILENAME"

But in the aftermath of the dojo the question came back to me and I did some research: Employing the search engine of my preference and looking into some of the original literature on shell scripting.

What I found came as a surprise to me. There are single voices that say things like

All the text books I've looked at always user upper case for all shell variables. While lower case variable names are permissible, uppercase is the convention.

But these voices are simply totally wrong. Practically all the literature I have surveyed now — see below for a list — even the literature going back to the very beginning, also uses lower case variables.

I have not bothered to puzzle out if these historic books apply specific conventions when to use upper or lower case variable names. Instead I looked for recent (read: relatively modern) shell coding conventions. There seem to be three serious style guides around that are not the (largely ignored) work of some individual offender:

  1. The Google "Shell Style Guide"
  2. The Gitlab "Shell scripting standards and style guidelines"
  3. The Chromium OS "Shell scripting standards and style guidelines"

Of these, only the first provides guidance on variable names:

  • Except for constants and environment variables (exported variables), name lower case and separate words by underscore. For example my_variable_name.
  • Constants and environment variables should be names all caps, again words separated with underscore.

Specifically so-called camel case — myVariableName — is frowned upon, according to this style guide. T

These rules are also (mostly) consistent with what I find in the literature listed below, with the possible exception of the Apple "Shell Scripting Primer" which uses all caps variables throughout (as I also do).



Due to legal pitfalls in Europe there is no comment section in this blog at the moment (sorry), but you can discuss this article or comment on its content ⮕ here on Mastodon.