AWS S3 Sync Backup Shell Script for Linux (aws cli, Cron, Logs)

aws s3 sync backup shell script

aws s3 sync in a shell script is the standard pattern for offsite backups without mounting object storage — highly searched alongside rsync tutorials. This script syncs a local path to a bucket prefix with logging and safe defaults.

What this script does

  • Uses aws s3 sync with explicit source and s3:// destination
  • Supports AWS_PROFILE or instance IAM role
  • Optional --delete mirror mode (commented by default)
  • Verifies aws CLI is installed before run
  • Logs start/end and exit code for cron mail

Prerequisites

  • AWS CLI v2 installed and configured
  • IAM permission s3:PutObject/ListBucket on target prefix
  • Enough bandwidth for backup window

Step 1: Save the script

sudo nano /usr/local/bin/s3-backup.sh
sudo chmod +x /usr/local/bin/s3-backup.sh

Step 2: Full script (scroll to read)

s3-backup.sh
#!/usr/bin/env bash
set -euo pipefail

SRC="${SRC:-/var/backups}"
DEST="${DEST:-s3://my-backup-bucket/prod/}"
AWS_PROFILE="${AWS_PROFILE:-default}"
LOG="/var/log/s3-backup.log"
DRY_RUN="${DRY_RUN:-0}"

log(){ echo "[$(date '+%F %T')] $*" | tee -a "$LOG"; }

command -v aws >/dev/null 2>&1 || { log "aws CLI not found"; exit 1; }
[[ -d "$SRC" ]] || { log "SRC not found: $SRC"; exit 1; }

export AWS_PROFILE

OPTS=(s3 sync "$SRC" "$DEST" --only-show-errors)
# Uncomment to mirror deletions (dangerous if SRC wrong):
# OPTS+=(--delete)

log "START ${OPTS[*]}"
if [[ "$DRY_RUN" == "1" ]]; then
  log "DRY_RUN=1 — would run: aws ${OPTS[*]}"
  exit 0
fi

if aws "${OPTS[@]}" >>"$LOG" 2>&1; then
  log "DONE s3 sync OK"
else
  ec=$?
  log "FAIL s3 sync exit=$ec"
  exit "$ec"
fi

Scroll inside the box to read the full script.

Step 3: Configure settings

AWS S3 sync backup shell script on Linux
AWS S3 sync backup shell script on Linux

Step 4: Test manually

aws sts get-caller-identity
DRY_RUN=1 /usr/local/bin/s3-backup.sh

Schedule with cron

sudo crontab -e

Add:

0 3 * * * /usr/local/bin/s3-backup.sh >> /var/log/s3-backup.log 2>&1

Related tutorials

Terminal screenshot is an original illustration created for Gnome IT Solutions (blog.gnomeitsolutions.com).