I run across many shell scripts with variables in all caps, and I've always thought that there is a severe misunderstanding with that. My understanding is that, by convention (and perhaps by necessity long ago), environment variables are in all-caps.
But in modern scripting environments like Bash, I have always preferred the convention of lower-case names for temporary variables, and upper-case ones only for exported (i.e. environment) variables. For example:
#!/usr/bin/env bash year=`date +%Y` echo "It is $year." export JAVA_HOME="$HOME/java"
That has always been my take on things. Are there any authoritative sources which either agree or disagree with this approach, or is it purely a matter of style?
By convention, environment variables (
EDITOR, ...) and internal shell variables (
BASH_VERSION, ...) are capitalized. All other variable names should be lower case.
Remember that variable names are case-sensitive; this convention avoids accidentally overriding environmental and internal variables.
Keeping to this convention, you can rest assured that you don't need to know every environment variable used by UNIX tools or shells in order to avoid overwriting them. If it's your variable, lowercase it. If you export it, uppercase it.
Any naming conventions followed consistently will always help. Here are a few helpful tips for shell variable naming:
Use all caps and underscores for exported variables and constants, especially when they are shared across multiple scripts or processes. Use a common prefix whenever applicable so that related variables stand out and won't clash with Bash internal variables which are all upper case.
Use "snake case" (all lowercase and underscores) for all variables that are scoped to a single script or a block.
Mixed case when local variable has some relationship with an environment variable, like:
Use a leading underscore for "private" variables and functions. This is especially relevant if you ever write a shell library where functions within a library file or across files need to share variables, without ever clashing with anything that might be similarly named in the main code.
Avoid camel case. This will minimize the bugs caused by case typos. Remember, shell variables are case sensitive.