Bash coding conventions

My shell scripting standards

  1. Prefer portability, but don't sacrifice security and whitespace awareness to it.
  2. Prefer builtins over external commands.
  3. But, use fast external commands to process very large inputs.
  4. Avoid unnecessary subshells and pipelines.
  5. Don't preoptimize.
  6. Learn the rules of quoting. Then, use quotes.
  7. Use functions to improve readability and control scope.
  8. Don't give scripts silly file extensions.
  9. Never change directory without checking that it worked.
  10. Eschew hobgoblins

A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines.

– Ralph Waldo Emerson

When to ignore the portability rule

  1. Use -execdir when appropriate with find.
  2. Use null separators when the toolset allows to avoid accidentally wordsplitting on whitespace.
  3. Learn all the glob extensions and use them.
  4. If your target systems all have BASH, don't bend over backwards to be POSIXLY_STRICT.
  5. Use here strings.

The best bash style guide I have come across is from Google.

There is also some additional advice from the Chromium project.

For learning bash, the Apple Developer Shell Scripting primer is excellent.

Using a style guide for bash is rather sensible, as it is full of tricks and unexpected and difficult to diagnose quirks. Thus, if you follow the same style all the time, you should only fall for each of those tricks once.

Tags:

Bash