Skip to content

Instantly share code, notes, and snippets.

@TimothyJones
Last active January 29, 2021 14:30
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save TimothyJones/74be211b740227e737b54ff3a1c0ec9b to your computer and use it in GitHub Desktop.
Save TimothyJones/74be211b740227e737b54ff3a1c0ec9b to your computer and use it in GitHub Desktop.
These are (currently) the only functions I recommend porting around when writing bash scripts
#!/bin/bash -eu
if [ -z "${LIB_ROBUST_BASH_SH:-}" ]; then
LIB_ROBUST_BASH_SH=included
function error {
echo "Error: ${1:-}"
}
# Check to see that we have a required binary on the path
function require_binary {
if [ -z "${1:-}" ]; then
error "${FUNCNAME[0]} requires an argument"
exit 1
fi
if ! [ -x "$(command -v "$1")" ]; then
error "The required executable '$1' is not on the path."
exit 1
fi
}
# Check to see that a required environment variable is set.
# Use it without the $, as in:
# require_env_var VARIABLE_NAME
# or
# require_env_var VARIABLE_NAME "Some description of the variable printed when it is missing"
function require_env_var {
var_name="${1:-}"
if [ -z "${!var_name:-}" ]; then
error "The required environment variable ${var_name} is empty"
if [ ! -z "${2:-}" ]; then
echo " - $2"
fi
exit 1
fi
}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment