# Backup Custom Scripts

Set up and use custom scripts for pre and/or post backup operations.

Custom scripts in Simplebackups allow you to extend the functionality of your backup process. This documentation will guide you through setting up and using custom scripts for pre and/or post backup operations. The examples provided will be written in Bash and demonstrate how to call a Python script.

## Requirements

- Access to your own server.
- Basic knowledge of Bash scripting.
- Python installed on your server.

### 1. Preparing Your Server

Ensure that your server meets the requirements mentioned above. Make sure Python is installed, and the path to the Python binary is defined in your environment.

### 2. Writing Bash Scripts

**Pre-Backup Script**

Create a Bash script that you want to run before the backup. Here's a simple example:

```shell
#!/bin/bash

# Your pre-backup operations go here
echo "Executing pre-backup operations..."
```

**Post-Backup Script**

Create another Bash script for post-backup operations. Here's an example:

```shell
#!/bin/bash

# Your post-backup operations go here
echo "Executing post-backup operations..."
```

### 3. Calling A Python Script

**Integrating Python Script**

Assuming you have a Python script named **`example.py`**, insert the following code to your pre backup script.

```shell
#!/bin/bash

# Define Python binary path
PYTHON_PATH="/usr/bin/python3"

# Your Python script
$PYTHON_PATH /path/to/your/example.py
```

### 4. Behavior When a Backup Fails

Your **post-backup script always runs** — even when the backup itself fails (for example an upload, compression, or encryption error, or a dropped SSH connection) — as long as the pre-backup script started. This makes pre- and post-backup scripts safe to use as a matched pair for setup and teardown.

For example, you can pause PostgreSQL WAL replay on a replica before the backup and resume it afterwards, confident the resume runs whether the backup succeeds or fails:

```shell
# Pre-backup script: pause replay on a replica
psql -c "SELECT pg_wal_replay_pause();"
```

```shell
# Post-backup script: always runs, even if the backup failed
psql -c "SELECT pg_wal_replay_resume();"
```

**Info:**
If the pre-backup script never started — for example the job failed during an early check before it ran — the post-backup script is skipped, since there is nothing to undo.

Run a test backup to ensure that your custom scripts are executed successfully before and/or after the backup job.

Remember to adapt the paths and commands according to your server setup and the location of your scripts. If you encounter any issues, refer to SimpleBackups documentation or reach out to support.
