5

Starting robust reliable and maintainable bash scripts

 1 year ago
source link: https://proinsias.github.io/tips/starting-robust-reliable-and-maintainable-bash-scripts
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Francis T. O'Donovan

Senior Data Science Manager at Hospital IQ – Planet discoverer, researcher, developer, geek.

Starting robust reliable and maintainable bash scripts

1 minute read

The set and shopt commands in bash are pretty powerful. One of the ways they can help you is by turning on some shell options that will make your bash scripts much more robust, reliable and maintainable. Aaron Maxwell has a nice discussion about this, but here I’ll record my own set of commands that I use at the top of my scripts.

#!/usr/bin/env bash

set -o errexit                # Exit on error. Append || true if you expect an error.
                              # Equivalent to `-e`.
set -o errtrace               # Exit on error inside any functions or subshells.
                              # Equivalent to `-E`.
set -o noclobber              # Don't allow overwriting files. Equivalent to `-C`.
set -o nounset                # Don't allow use of undefined vars.
                              # Use ${VAR:-} to use an undefined VAR. Equivalent to `-u`.
set -o pipefail               # Produce a failure return code if any pipeline command errors.
shopt -s failglob             # Cause globs that don't get expanded to cause errors.
shopt -s globstar 2>/dev/null # Match all files and zero or more sub-directories.

Note that I use the long names rather than the short equivalents. When writting scripts (as opposed to typing one-off commands), I prefer to use the long names, as I easily forget what short options refer to.

Another useful option is set -o xtrace or set -x, which will print a trace of commands in the script – though you may find this overkill, and I typically don’t include it.

Tags: bash nix tips

Categories: tips

Updated: October 26, 2022

Previous Next


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK