Skip to content

Instantly share code, notes, and snippets.

@fredrike
Last active June 9, 2025 05:56
Show Gist options
  • Select an option

  • Save fredrike/bbc32e0e51ace094f8b16c0c73fdfc46 to your computer and use it in GitHub Desktop.

Select an option

Save fredrike/bbc32e0e51ace094f8b16c0c73fdfc46 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Define variables
RESTIC_PASSWD="/home/<USERNAME>/.restic_password"
BACKUP_SOURCE="/<LOCATION_TO_BACKUP>"
BACKUP_REPO="<PATH_TO_STORE_BACKUP>/<BACKUP_NAME>"
WEBHOOK_URL="https://hc-ping.com/<uuid>"
KEEP_OPTIONS="--keep-hourly 2 --keep-daily 6 --keep-weekly 3 --keep-monthly 1"
RUN_UUID=$(cat /proc/sys/kernel/random/uuid)
# Sending start ping to measure runtime
curl -fsS -m 10 --retry 5 "$WEBHOOK_URL/start?rid=$RUN_UUID"
# Function to run a command and capture its output to a temp file
run_command() {
local CMD="$1" # Takes the first argument as the command to be executed
TMP_FILE=$(mktemp)
echo "Running: $CMD" >> "$TMP_FILE" # Logs the command being executed to $TMP_FILE
$CMD >> "$TMP_FILE" 2>&1 # Executes the command and redirects both stdout and stderr to $TMP_FILE
STATUS = $? # Checks the exit status of the last command
OUTPUT=$(cat "$TMP_FILE")
# Log output to Heathchecks
curl -fsS -m 10 --retry 5 --data-raw "$OUTPUT" "$WEBHOOK_URL/log?rid=$RUN_UUID"
rm "$TMP_FILE"
if [ $STATUS -ne 0 ]; then
# Sends ping to Heathchecks with the failure code
# Deletes the TMP_FILE
# Exits the bash script
curl -m 10 --retry 5 "$WEBHOOK_URL/$STATUS?rid=$RUN_UUID"
exit $STATUS
fi
}
# Perform Restic unlock and capture output
run_command "restic -p $RESTIC_PASSWD -r $BACKUP_REPO unlock"
# Perform Restic backup
run_command "restic -p $RESTIC_PASSWD -r $BACKUP_REPO backup $BACKUP_SOURCE"
# Perform Restic forget
run_command "restic -p $RESTIC_PASSWD -r $BACKUP_REPO forget $KEEP_OPTIONS --prune --cleanup-cache"
# Send success
curl -fsS -m 10 --retry 5 -o /dev/null "$WEBHOOK_URL?rid=$RUN_UUID"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment