Are there naming conventions for variables in shell scripts?

Most languages have naming conventions for variables, the most common style I see in shell scripts is MY_VARIABLE=foo. Is this the convention or is it only for global variables? What about variables local to the script?

Asked By: Garrett Hall

||

Environment variables or shell variables introduced by the operating system, shell startup scripts, or the shell itself, etc., are usually all in CAPITALS1.

To prevent your variables from conflicting with these variables, it is a good practice to use lower_case variable names.


1A notable exception that may be worth knowing about is the path array, used by the zsh shell. This is the same as the common PATH variable but represented as an array.

Answered By: jippie

Yes, there are full code style conventions for bash, including variable names. For example, here’s Google’s Shell Style Guide.

As a summary for the variable names specifically:

Variable Names: Lower-case, with underscores to separate words. Ex: my_variable_name

Constants and Environment Variable Names: All caps, separated with underscores, declared at the top of the file. Ex: MY_CONSTANT

Answered By: Anonsage

Underscores to separate words seem to be the best way to go.
I have a few reasons to prefer snake_case over camelCase when I’m free to choose:

  1. Flexible: You can use upper case and lower case (e.g. MY_CONSTANT and my_variable);
  2. Consistent: The digits can be separated to make the number more readable (e.g. 1_000_000_000) and this feature is supported in many programming languages;
  3. Common: Common at the point the regex w handles underscores like word characters and numbers ([a-zA-Z0-9_]).
Answered By: isar
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.