by Leon Rosenshein

Code Golf

Code golf is fun and all, and sometimes it can be fun to see just how terse you can write something and still have it work but it's a good idea to

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability.

The comma operator in C/C++ is a great example. You can save a handful of keystrokes, but it's almost never a good idea. 

Another place that people are often a little too terse is bash scripting. Especially when you're sharing scripts or saving them for future use. When you're writing a script it's very tempting to stop as soon as it's completed its task once. And if you delete it right after that it's probably OK. But if you're going to share it or save it for future use experience says that you probably want to be a little more verbose. And probably a little more rigorous. Maybe even a lot more.

Here's a few good ideas to use when building scripts that are going to be used multiple times. Especially if they're going to be used by others on random machines as part of a complex workflow.

Fail Fast: Use set -euo pipefail to make your script stop as soon as something goes wrong so you don't make things worse

trap: Use handlers to ensure cleanup in error conditions. You can handle signals, ERR, and EXIT something like:

on_error() {

  # Log message and cleanup

}

trap "on_error" ERR

shellcheck: is part of the `rNA` toolset. Use it and pay attention to the results. Consistency is a good thing.

Use default values for variables where possible: Bash variable expansion lets you get the value of a variable or a default if it's unset. You can use it to make positional command line variables optional with something like

FOO=${2:-default} # If command line option 2 is not set or null, use default.

Include common functions via shared files: The `rNA` repo has some common helpers to deal with MacOS vs Ubuntu. They might be helpful. You might have something similar for your team.

Clean up after yourself: Consider using a `/tmp` folder then deleting it when you're done. Cleanup would be a good use of a trap.

What are your favorite bash scripting tips?