Tue Oct 27 2020Journal

Bash useful utilities

avatar
Xavier Bruhiere
linkedintwitterfacebook
intro picture
HEY:

Work in progress so considere this more like a brain dump than battle-tested knowledge (although the ideas do come from the trenches).

Bash script template

All my scripts automatically start with the lines below. I've been experimenting with various guru-level bash script templating and all proved to be of little value, except this very simple one.

#! /usr/bin/env bash

# unofficial strict mode
set -eo pipefail

# … useful functions like `_log()`

# … actual logic

The env-based shebang is more portable than hardcoded bath.

The flags are well explained by Aaron Maxwell in this must-read. In a nutshell, it will make your script behave like you would expect from a program, like stopping on errors.

I no longer source common libraries and instead copy paste. Because O(copypasting) < O(unix path management).

Useful functions

Bash is quite raw so a few colors in your output can go a long way to save your eyes and impress your tech lead.

YELLOW='\033[1;33m'
CYAN='\033[1;36m'
NC='\033[0m' # No Color

_log() {
    # `date` note: `%T` is the time up to second, `%6N` is the number of
    # nanoseconds rounded to the microseconds (6 digits)
    printf "[${CYAN} $(date '+%T.%6N') ${NC}]${YELLOW} $@ ${NC}\n"
}




#utils#sh#tips#code

Read Next

Google Distill: Everything data pros need to know

Maybe you want your paper to help your peers to progress, build upon it, and recognize you as a valuable contributor to their field. If so, then the Distill publishing platform could really help you out.