cheat-sheets

Cheat sheets for various stuff

View the Project on GitHub bertvv/cheat-sheets

Bash best practices

An attempt to bring order in good advice on writing Bash scripts I collected from several sources.

General

Variables

Substitution

Output and redirection

Functions

Bash can be hard to read and interpret. Using functions can greatly improve readability. Principles from Clean Code apply here.

Cleanup code

An idiom for tasks that need to be done before the script ends (e.g. removing temporary files, etc.). The exit status of the script is the status of the last statement before the finish function.

finish() {
  result=$?
  # Your cleanup code here
  exit ${result}
}
trap finish EXIT ERR

Source: Aaron Maxwell, How “Exit Traps” can make your Bash scripts way more robust and reliable.

Writing robust scripts and debugging

Bash is not very easy to debug. There’s no built-in debugger like you have with other programming languages. By default, undefined variables are interpreted as empty strings, which can cause problems further down the line. A few tips that may help:

Shell script template

An annotated template for Bash shell scripts:

For now, see https://github.com/bertvv/dotfiles/blob/master/.vim/templates/sh

Resources

Templates

Portable shell scripts

Fun