Skip to content

Instantly share code, notes, and snippets.

@ozturkoktay
Created January 16, 2026 18:49
Show Gist options
  • Select an option

  • Save ozturkoktay/db7106c8bfe006da9f05e56d49105397 to your computer and use it in GitHub Desktop.

Select an option

Save ozturkoktay/db7106c8bfe006da9f05e56d49105397 to your computer and use it in GitHub Desktop.
Git corruption recovery
#!/bin/bash
# =====================================================
# Git Recovery Script
# =====================================================
# Purpose:
# This script is designed to safely recover a local Git repository
# when the .git folder is corrupted or lost, while preserving all
# local changes and merging them with a remote repository.
#
# What it does:
# 1. Creates a backup of your current repository and its .git folder.
# 2. Initializes a fresh Git repository.
# 3. Commits all your current local code to preserve it.
# 4. Adds the remote repository and fetches its content.
# 5. Merges the remote branch into your local commit.
# - Automatically keeps your local files if there are conflicts
# (both code and binary files like models).
# 6. Pushes the recovered repository back to the remote.
#
# When to use:
# - Your local repository's .git folder is corrupted or empty.
# - You have local changes that are newer than the remote.
# - You want to recover a repository without losing any local work.
# - You want a clean repository setup with the remote synced.
#
# How to use:
# ./git_recover.sh /path/to/your/repo <remote_url>
# Example:
# ./git_recover.sh ~/Desktop/AcSYS/acsys-ai-vision-gui \
# https://github.com/AcSYS-Engineering/acsys-ai-vision-gui.git
set -e
REPO_PATH="$1"
REMOTE_URL="$2"
if [ -z "$REPO_PATH" ] || [ -z "$REMOTE_URL" ]; then
echo "Usage: $0 /path/to/repo remote_url"
exit 1
fi
if [ ! -d "$REPO_PATH" ]; then
echo "Error: Repository path does not exist: $REPO_PATH"
exit 1
fi
cd "$REPO_PATH"
RECOVERY_DIR="$(dirname "$REPO_PATH")/git_recovery_snapshot"
mkdir -p "$RECOVERY_DIR"
REPO_NAME="$(basename "$REPO_PATH")"
cp -r "$REPO_PATH" "$RECOVERY_DIR/"
if [ -d ".git" ]; then
mv .git .git_corrupted
fi
git init
git branch -M main
git remote add origin "$REMOTE_URL"
git add .
git commit -m "Initial commit of recovered local code"
git fetch origin
git merge origin/main --allow-unrelated-histories || true # merge may produce conflicts
git checkout --ours .
git add .
git commit -m "Recovered local code and merged remote safely"
git push -u origin main
echo "Git recovery complete for $REPO_NAME"
echo "Backup snapshot is stored at $RECOVERY_DIR"
echo "Local code preserved and merged safely with remote."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment