Command Hook Examples
Introduction
Command hooks are a powerful way to extend Backrest's capabilities. They allow you to run arbitrary shell commands in response to lifecycle events. This doc shows examples of command hooks.
Command Hook Options
When run on CONDITION_SNAPSHOT_START
command hooks have the ability to send control signals to Backrest based on the exit status of the script. The handling of the exit status is configured by the Error Behavior
field. The following options are available:
ON_ERROR_CANCEL
- If the script exits with a non-zero status, the backup operation will be canceled.ON_ERROR_FATAL
- If the script exits with a non-zero status, it is treated as a backup failure and error notifications are triggered.ON_ERROR_IGNORE
- If the script exits with a non-zero status, the backup operation will continue and the error will be ignored.
Examples
Notify a healthcheck service
Ping a healthcheck service (e.g. https://healthchecks.io/ in the example) to notify it of backup status (or failure) using a command hook.
Note that this hook example takes advantage of the fact that the hook is a golang template to render different commands based on whether an error occurred.
Condition CONDITION_SNAPSHOT_END
Script
#!/bin/bash
{{ if .Error -}}
curl -fsS --retry 3 https://hc-ping.com/your-uuid/fail
{{ else -}}
curl -fsS --retry 3 https://hc-ping.com/your-uuid
{{ end -}}
Error Behavior: ON_ERROR_IGNORE
(MacOS) Show system notification
Show a system notification using the osascript
command on MacOS.
Condition CONDITION_SNAPSHOT_END
, CONDITION_PRUNE_ERROR
, CONDITION_CHECK_ERROR
Script
#!/bin/bash
{{ if .Error -}}
osascript -e 'display notification "{{ .ShellEscape .Task }} failed" with title "Backrest"'
{{ else -}}
osascript -e 'display notification "{{ .ShellEscape .Task }} succeeded" with title "Backrest"'
{{ end -}}
Check for internet connectivity
Add a hook to check for internet connectivity before running a backup.
Condition CONDITION_SNAPSHOT_START
Script
#!/bin/bash
if ping -q -c 1 -W 1 google.com >/dev/null; then
echo "Internet connection is up"
exit 0
else
echo "Internet connection is down"
exit 1
fi
Error Behavior: ON_ERROR_CANCEL
Check that a target directory exists
Add a hook to check that a target directory exists before running a backup.
Condition CONDITION_SNAPSHOT_START
Script
#!/bin/bash
if [ -d /path/to/backup ]; then
echo "Backup directory exists"
exit 0
else
echo "Backup directory does not exist"
exit 1
fi
Error Behavior: ON_ERROR_CANCEL
Check that the battery is above a certain level
Add a hook to check that the battery is above a certain level before running a backup.
Condition CONDITION_SNAPSHOT_START
Script
#!/bin/bash
if [ $(cat /sys/class/power_supply/BAT0/capacity) -gt 80 ]; then
echo "Battery level is above 20%"
exit 0
else
echo "Battery level is below 20%"
exit 1
fi
Error Behavior: ON_ERROR_CANCEL