Boilerplate for Bash scripts


This is a starter for making a robust bash script. Comments inline.

#!/usr/bin/env bash

set -o errexit
set -o pipefail
set -o nounset

#
# load an .env file if it exists
#
ENV_FILE="./.env"
if [ -f "${ENV_FILE}" ]; then
    echo "INFO: loading '${ENV_FILE}'!"
    export $(cat "${ENV_FILE}")
fi

#
# check for required parameters
#
RANDOM_ARG=${1:-BAD}
if [ "${RANDOM_ARG}" = "BAD"  ]; then
    echo "USAGE: migrate.sh RANDOM_ARG"
    echo "       RANDOM_ARG is PARTNER-ENVIRONMENT, like ie-prod or usa-test"
    exit 1
fi

# 
# check for required files
#
RANDOM_FILE="./file.txt"
if [ ! -f "${RANDOM_FILE}" ]; then
    echo "ERROR: no file '${RANDOM_FILE}'!"
    exit 2
fi

#
# check for required env vars
#
REQUIRED_VARS=( A B C )
declare -a MISSING_VARS
for REQUIRED_VAR in "${REQUIRED_VARS[@]}"
do
	REQUIRED_VALUE="${!REQUIRED_VAR:-BAD}"
	if [ "${REQUIRED_VALUE}" = "BAD"  ]; then
		MISSING_VARS+=(${REQUIRED_VAR})
	fi
done

if [ ${#MISSING_VARS[@]} -gt 0 ]; then
    echo "ERROR: missing env vars: ${MISSING_VARS[*]}"
    exit 3
fi

echo "INFO: starting at $(date -u +%Y-%m-%dT%H:%M:%SZ)"

echo "INFO: complete at $(date -u +%Y-%m-%dT%H:%M:%SZ)"

Date: 2019-11-04

Tags:  bash

Share: