From 6c7b38cf18d09b2f56547a62d20806d45f86626d Mon Sep 17 00:00:00 2001 From: Alan_Shan Date: Sat, 25 Apr 2026 17:36:09 +0300 Subject: [PATCH] Add sync_with_git.sh --- sync_with_git.sh | 62 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 sync_with_git.sh diff --git a/sync_with_git.sh b/sync_with_git.sh new file mode 100644 index 0000000..595db32 --- /dev/null +++ b/sync_with_git.sh @@ -0,0 +1,62 @@ +#!/bin/bash + +# ============================================================================== +# Script Description: +# This script connects an existing local directory to a remote Git repository. +# It requires the SSH URL of the Git repository as an input argument. +# +# Process: +# 1. Initializes a new local Git repository. +# 2. Adds the provided URL as the remote 'origin'. +# 3. Fetches the remote repository data. +# 4. Checks for differences between the local files and 'origin/master'. +# 5. If there are no differences, it sets up tracking for the master branch +# and performs a hard reset to synchronize exactly with the remote. +# +# Usage: +# ./connect_git.sh +# +# Example: +# ./connect_git.sh git@github.com:username/repository.git +# ============================================================================== + +# Check if the repository URL argument is provided +if [ -z "$1" ]; then + echo "Error: No repository SSH URL provided." + echo "Usage: $0 " + exit 1 +fi + +REPO_URL=$1 +BRANCH="master" + +echo "Initializing Git repository..." +git init + +echo "Adding remote 'origin' -> $REPO_URL" +git remote add origin "$REPO_URL" + +echo "Fetching from origin..." +git fetch origin + +# Check differences between the local working directory and the remote branch. +# Using 'git diff --quiet origin/master' safely checks without needing HEAD to exist. +echo "Checking differences..." +if git diff --quiet "origin/$BRANCH"; then + echo "No differences found between local folder and remote origin/$BRANCH." + + echo "Setting up tracking and aligning with remote..." + # Ensure we are on the master branch + git checkout -B "$BRANCH" + # Set the upstream tracking branch + git branch --set-upstream-to="origin/$BRANCH" "$BRANCH" + # Hard reset to match the remote exactly + git reset --hard "origin/$BRANCH" + + echo "Success! The local folder is now completely linked to the remote repository." +else + echo "Notice: Differences exist between the local files and origin/$BRANCH." + echo "Tracking was not set automatically. You can review differences using:" + echo " git diff origin/$BRANCH" + exit 1 +fi