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:
set -euo pipefailto improve how your script deals with undeclared variables and non-zero exit codes.
IFS=$'\n\t'so that array elements are split in a predictable way.
- When defining functions, return data with
returnkeyword 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
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.