DEV Community

Cover image for Make your shell scripts more bugproof with a few simple habits
Pieter D
Pieter D

Posted on

Make your shell scripts more bugproof with a few simple habits

Your terminal can do some really cool things. The | operator was a stroke of genius. It lets you take the output of one command and feed it to another, chaining together a few simple tools to perform a bigger automated task.

Shell scripts are a natural extension of your terminal's power. Creating ready-to-run recipes for later use? Sweet. But once you start using these scripts for more advanced things, you run into some unfortunate Bash quirks. For example: when a part of your script produces an error, the rest of the script will still be executed, making its behavior unpredictable.

There are some habits that you can adopt right now to make writing shell scripts easier.

Here's the gist of it if you don't need further explanation:

  • Add set -euo pipefail to improve how your script deals with undeclared variables and non-zero exit codes.
  • Add IFS=$'\n\t' so that array elements are split in a predictable way.
  • When defining functions, return data with echo instead of return. The return keyword doesn't do the same thing as in other languages.
  • Returning arrays from functions is not really possible. As a bad but easy workaround, you can pass array return values via a global variable.
  • Keep your whitespace in mind. Confusingly, if [ FOO=='bar' ] will overwrite the value of $FOO. if [ FOO = 'bar' ] will perform a string equality check.

Alternatively, for complex tasks, you'll probably have an easier time using a different scripting language like Python, Ruby or Perl.

Additional reading

Unofficial bash strict mode
Your bash scripts are rubbish, use another language

Discussion (0)