Skip to main content
hooksSource-backedReview first Safety Privacy

Auto Save Backup - Hooks

Automatically creates timestamped backups of files before modification to prevent data loss. This hook runs before file editing operations (Edit, Write, Multiedit) and creates versioned backups in a centralized .backups directory with ISO 8601-compliant timestamps including nanoseconds for collision prevention.

by JSONbored·added 2025-09-19·
HarnessClaude Code
Trigger:PreToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/hooks, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/auto-save-backup.mdx
Safety notes
Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notes
Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-19

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

0/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.

2 areas
  • SafetyPermissions & scopesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
  • PrivacyCredentials & tokensReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Safety notes

  • Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.

Privacy notes

  • Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Schema details

Install type
cli
Reading time
1 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://code.claude.com/docs/en/hooks
Runtime and command metadata
Trigger
PreToolUse
Script language
bash
Script body
#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if file exists before backing up
if [ -f "$FILE_PATH" ]; then
  echo "💾 Creating backup for $FILE_PATH..." >&2
  
  # Create backups directory
  mkdir -p .backups
  
  # Generate timestamped backup filename
  BASENAME=$(basename "$FILE_PATH")
  TIMESTAMP=$(date +%Y%m%d_%H%M%S)
  BACKUP_NAME="${BASENAME%.*}_${TIMESTAMP}.${BASENAME##*.}"
  
  # Create backup
  cp "$FILE_PATH" ".backups/$BACKUP_NAME" 2>/dev/null || true
  
  if [ $? -eq 0 ]; then
    echo "✅ Backup created: .backups/$BACKUP_NAME" >&2
  else
    echo "⚠️ Backup failed for $FILE_PATH" >&2
  fi
else
  echo "📝 Creating new file $FILE_PATH (no backup needed)" >&2
fi

exit 0
Full copyable content
{
  "hooks": {
    "preToolUse": {
      "script": "./.claude/hooks/auto-save-backup.sh",
      "matchers": [
        "edit",
        "write",
        "multiedit"
      ]
    }
  }
}

About this resource

Features

  • Automatic timestamped backups before file modification using ISO 8601 format with nanosecond precision for collision prevention
  • Organized backup storage in .backups directory with hierarchical structure and configurable retention policies
  • Filename format: filename_YYYYMMDD_HHMMSS_NS.ext supporting rapid file edits without timestamp collisions
  • Support for all file editing operations including Edit, Write, and Multiedit with batch backup creation
  • Version history maintenance with automatic cleanup of old backups based on age or count limits
  • Silent failure handling to prevent workflow interruption with graceful error recovery and logging
  • Disk space management with pre-backup checks and automatic cleanup of oldest backups when space is limited
  • Efficient file copying using optimized cp commands with preservation of file permissions, timestamps, and metadata

Use Cases

  • Automatic version control for critical configuration files ensuring recovery from accidental modifications
  • Safety net during development and debugging sessions providing rollback capability for experimental changes
  • Recovery from accidental file modifications with easy restoration from timestamped backup files
  • Maintaining edit history without git commits for files not tracked in version control
  • Protection during bulk file operations ensuring all modified files have backups before changes
  • Development workflow safety net for rapid prototyping and experimentation with automatic backup creation

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/auto-save-backup.sh
  3. Make executable: chmod +x .claude/hooks/auto-save-backup.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. Alternative: Use the interactive /hooks command in Claude Code

Config paths

  • Local (not committed): .claude/settings.local.json
  • User settings (global): ~/.claude/settings.json
  • Project-wide (committed): .claude/settings.json

Requirements

  • Claude Code CLI installed
  • Project directory initialized
  • Bash shell available
  • jq installed (for JSON parsing)
  • Standard Unix utilities: cp, date, find, mkdir (built into most Unix-like systems)
  • Sufficient disk space for backup storage (backups stored in .claude/backups/ directory)

Hook Configuration

{
  "hooks": {
    "preToolUse": {
      "script": "./.claude/hooks/auto-save-backup.sh",
      "matchers": ["edit", "write", "multiedit"]
    }
  }
}

Hook Script

#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if file exists before backing up
if [ -f "$FILE_PATH" ]; then
  echo "💾 Creating backup for $FILE_PATH..." >&2

  # Create backups directory
  mkdir -p .backups

  # Generate timestamped backup filename
  BASENAME=$(basename "$FILE_PATH")
  TIMESTAMP=$(date +%Y%m%d_%H%M%S)
  BACKUP_NAME="${BASENAME%.*}_${TIMESTAMP}.${BASENAME##*.}"

  # Create backup
  cp "$FILE_PATH" ".backups/$BACKUP_NAME" 2>/dev/null || true

  if [ $? -eq 0 ]; then
    echo "✅ Backup created: .backups/$BACKUP_NAME" >&2
  else
    echo "⚠️ Backup failed for $FILE_PATH" >&2
  fi
else
  echo "📝 Creating new file $FILE_PATH (no backup needed)" >&2
fi

exit 0

Examples

Auto Save Backup Hook Script

Complete hook script that creates timestamped backups before file modifications with nanosecond precision

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r ".tool_input.file_path // .tool_input.path // \"\"")
if [ -z "$FILE_PATH" ]; then exit 0; fi
if [ -f "$FILE_PATH" ]; then
  mkdir -p .backups
  BASENAME=$(basename "$FILE_PATH")
  TIMESTAMP=$(date +%Y%m%d_%H%M%S_%N)
  BACKUP_NAME="${BASENAME%.*}_${TIMESTAMP}.${BASENAME##*.}"
  cp "$FILE_PATH" ".backups/$BACKUP_NAME" 2>/dev/null || true
  if [ $? -eq 0 ]; then
    echo "Backup created: .backups/$BACKUP_NAME" >&2
  fi
fi
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable automatic backups before file edits, writes, and multiedits

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write|Multiedit",
        "hooks": [
          {
            "type": "command",
            "command": "./.claude/hooks/auto-save-backup.sh"
          }
        ]
      }
    ]
  }
}

Backup with Disk Space Management

Enhanced hook script with automatic cleanup of old backups when disk space is limited

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r ".tool_input.file_path")
if [ -f "$FILE_PATH" ]; then
  mkdir -p .backups
  BASENAME=$(basename "$FILE_PATH")
  TIMESTAMP=$(date +%Y%m%d_%H%M%S_%N)
  BACKUP_NAME="${BASENAME%.*}_${TIMESTAMP}.${BASENAME##*.}"

  # Check disk space before backup
  AVAILABLE=$(df -BG .backups | tail -1 | awk '{print $4}' | sed 's/G//')
  if [ "$AVAILABLE" -lt 1 ]; then
    find .backups -type f -mtime +30 -delete 2>/dev/null
  fi

  cp "$FILE_PATH" ".backups/$BACKUP_NAME" 2>/dev/null || true
fi
exit 0

Multiedit Backup Support

Hook script that handles Multiedit operations by backing up all files in the edits array

#!/usr/bin/env bash
INPUT=$(cat)
if echo "$INPUT" | jq -e ".tool_input.edits" &> /dev/null; then
  mkdir -p .backups
  echo "$INPUT" | jq -r ".tool_input.edits[].file_path" | while read -r FILE_PATH; do
    if [ -f "$FILE_PATH" ]; then
      BASENAME=$(basename "$FILE_PATH")
      TIMESTAMP=$(date +%Y%m%d_%H%M%S_%N)
      BACKUP_NAME="${BASENAME%.*}_${TIMESTAMP}.${BASENAME##*.}"
      cp "$FILE_PATH" ".backups/$BACKUP_NAME" 2>/dev/null || true
    fi
  done
fi
exit 0

Backup with Retention Policy

Advanced hook script with automatic retention policy limiting backups to last 50 versions per file

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r ".tool_input.file_path")
if [ -f "$FILE_PATH" ]; then
  mkdir -p .backups

  # Retention policy: keep last 50 backups per file
  BASENAME=$(basename "$FILE_PATH")
  FILE_PREFIX="${BASENAME%.*}_"

  # Count existing backups for this file
  BACKUP_COUNT=$(find .backups -name "${FILE_PREFIX}*" | wc -l)

  if [ "$BACKUP_COUNT" -ge 50 ]; then
    find .backups -name "${FILE_PREFIX}*" -type f -printf '%T@ %p\n' | sort -n | head -n -50 | cut -d ' ' -f2- | xargs rm -f 2>/dev/null
  fi

  TIMESTAMP=$(date +%Y%m%d_%H%M%S_%N)
  BACKUP_NAME="${BASENAME%.*}_${TIMESTAMP}.${BASENAME##*.}"
  cp "$FILE_PATH" ".backups/$BACKUP_NAME" 2>/dev/null || true
fi
exit 0

Troubleshooting

PreToolUse hook runs but backup directory not created

Verify mkdir permissions in project root. Check disk space: df -h. Ensure script runs with correct CWD: pwd >&2 in hook. Create .backups manually if needed: mkdir -p .backups. Check filesystem permissions on project directory.

Backup created but original file modification fails after

PreToolUse only creates backup, doesn't block edits. Check subsequent tool execution logs. Verify hook exits with 0 (non-blocking). Review tool output for actual edit errors. Ensure backup operation completes before file modification.

Timestamp collisions when editing same file rapidly

Add nanoseconds to timestamp: date +%Y%m%d*%H%M%S*%N. Or use hash suffix: ${TIMESTAMP}_$(md5sum file | cut -c1-8). Implement collision detection and retry logic. Use ISO 8601 format with nanoseconds for better precision.

Hook backs up new files that don't exist yet on Write

Verify [ -f "$FILE_PATH" ] check works correctly. Check TOOL_NAME to distinguish edit vs write: if [["$TOOL_NAME" == "edit"]]. Skip backup for new file creation. Use PreToolUse only for Edit operations, not Write.

Backup directory grows unbounded filling disk space

Add retention policy: find .backups -mtime +30 -delete. Implement backup rotation script. Use git for versioning instead. Add size limit checks before creating backups. Limit backups per file: find .backups -name "file_*" | tail -n +50 | xargs rm.

Backup operation takes too long on large files

Add file size check before backup: [ $(stat -f%z file) -lt 10000000 ]. Use rsync for large files: rsync -a file .backups/backup_name. Consider excluding large files from backup. Add timeout wrapper: timeout 10s cp file backup.

Backup files have wrong permissions or ownership

Use cp -p to preserve permissions: cp -p file backup. Check umask settings. Verify backup directory permissions: chmod 700 .backups. Use rsync -a for better metadata preservation: rsync -a file backup.

Multiedit operations only backup first file

Check if FILE_PATH is array in multiedit context. Parse all paths: jq -r '.tool_input.edits[].file_path'. Loop through each file for backup. Verify jq parsing handles arrays correctly. Test with multiple files in edits array.

Source citations

Add this badge to your README

Show that Auto Save Backup - Hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/auto-save-backup.svg)](https://heyclau.de/entry/hooks/auto-save-backup)

How it compares

Auto Save Backup - Hooks side by side with 2 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Field

Automatically creates timestamped backups of files before modification to prevent data loss. This hook runs before file editing operations (Edit, Write, Multiedit) and creates versioned backups in a centralized .backups directory with ISO 8601-compliant timestamps including nanoseconds for collision prevention.

Open dossier

A Stop hook that syncs your changed files to cloud storage when a Claude Code session ends, using rclone to push to S3, Google Cloud Storage, or any of its 70+ supported backends.

Open dossier

A PostToolUse hook that watches for edits to Docker-related files (Dockerfile, docker-compose, .dockerfile, .dockerignore).

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy
BrandAWS logoAWSDocker logoDocker
Categoryhookshookshooks
Sourcesource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONbored
Added2025-09-192025-09-192025-09-19
Platforms
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically at session end and can create compressed archives of modified git files. Uploads backups through AWS CLI, Google Cloud SDK, or rclone when those tools and bucket variables are configured. Writes a temporary archive under /tmp when using the rclone fallback and removes it after the copy attempt.Runs automatically after write or edit activity on Dockerfile, docker-compose, dockerfile, and dockerignore paths. Invokes docker build or docker compose build and can consume CPU, disk, network, and local Docker daemon resources. Uses the Dockerfile directory or compose-file directory as the build context, so incorrect paths can include more files than expected.
Privacy notesReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Sends modified file contents to the configured cloud storage destination. Uses locally configured cloud credentials and bucket environment variables but does not define or manage them. Backup archives may include source code, docs, generated files, and any unignored local changes listed by git diff.Reads Docker-related files and may send build context files to the local Docker daemon during image builds. Build logs may reveal image names, service names, dependency URLs, and package-install output. Prints the first lines of .dockerignore files to local hook output when those files are edited.
Prerequisites— none listed— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/auto-save-backup.sh && chmod +x .claude/hooks/auto-save-backup.sh
mkdir -p .claude/hooks && touch .claude/hooks/cloud-backup-on-session-stop.sh && chmod +x .claude/hooks/cloud-backup-on-session-stop.sh
mkdir -p .claude/hooks && touch .claude/hooks/docker-container-auto-rebuild.sh && chmod +x .claude/hooks/docker-container-auto-rebuild.sh
Config
{
  "hooks": {
    "preToolUse": {
      "script": "./.claude/hooks/auto-save-backup.sh",
      "matchers": [
        "edit",
        "write",
        "multiedit"
      ]
    }
  }
}
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/cloud-backup-on-session-stop.sh"
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/docker-container-auto-rebuild.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimed
Open 3 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.