BASH
Initialize Git Repository and Add Remote
Quickly set up a new Git repository in your project directory, add an initial commit, and link it to a remote origin on GitHub, GitLab, or another service.
#!/bin/bash
# --- Configuration ---
REPO_DIR="." # Directory to initialize Git in (current directory by default)
REMOTE_URL="[email protected]:your-user/your-repo.git" # IMPORTANT: Update this to your remote URL
# --- Script Start ---
echo "Initializing Git repository in $REPO_DIR..."
cd "$REPO_DIR" || { echo "Error: Directory $REPO_DIR not found."; exit 1; }
# Check if Git is already initialized
if [ -d ".git" ]; then
echo "Git repository already initialized in $REPO_DIR. Skipping 'git init'."
else
git init
echo "Git repository initialized."
fi
# Add all files and make initial commit
git add .
git commit -m "Initial project setup" || echo "No changes to commit (might be an empty repo or already committed)."
# Ensure default branch is 'main'
CURRENT_BRANCH=$(git branch --show-current)
if [ "$CURRENT_BRANCH" != "main" ]; then
git branch -M main
echo "Default branch set to 'main'."
fi
# Add remote origin
if git remote get-url origin &>/dev/null; then
echo "Remote 'origin' already exists. Updating URL to $REMOTE_URL"
git remote set-url origin "$REMOTE_URL"
else
git remote add origin "$REMOTE_URL"
echo "Remote 'origin' added with URL: $REMOTE_URL"
fi
echo "Pushing initial commit to remote..."
git push -u origin main
echo "Git setup complete."
How it works: This script automates the initial setup for a new Git repository. It first checks if Git is already initialized, then stages all current files, creates an initial commit, ensures the main branch is named `main`, and finally adds and pushes to a specified remote origin. This streamlines the process of getting a new project under version control efficiently.