#!/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