Robust shell scripting

Topics: Linux Shell

Robust shell scripts handle failures and cleanup explicitly, as in the example below.

Subtopics

Example script

#!/bin/bash

# Set script behaviour
set -o errexit
set -o pipefail
set -o nounset
set -o errtrace

# Trap signals
function exit_trap {
	local exit_code=$1
	local line_no=$2
	
	if [ "$exit_code" != "0" ]; then
		echo "Error $exit_code occurred on $line_no"
	fi
	
	echo -n "Exit, cleanup ... "
	rm -rf "$TEMP_FILE"
	echo "ok"
}
trap 'exit_trap $? $LINENO' EXIT SIGINT SIGTERM

TEMP_FILE=$(mktemp)

# Safely get the PWD
DIR=$(cd "$(dirname "$0")"; pwd -P)

# Pre-flight checks
for cmd in mv rm mktemp cat; do
	type "$cmd" >/dev/null 2>&1 || {
		echo "$cmd is required but not installed. Aborting." >&2
		exit 1
	}
done

# Default values
CONTENT=${CONTENT:-$(cat)}
TARGET_FILE=${TARGET_FILE:-"$DIR/target.txt"}

# Output context, Progress and errors
echo -n "Write content to temp file ... "
echo "$CONTENT" > "$TEMP_FILE"
echo "ok"

echo -n "Move temp file to target ... "
mv "$TEMP_FILE" "$TARGET_FILE"
echo "ok"

Bookmarks

Questions