InterviewPitch
Git interview questions

Git Interview Questions with Answers

Most Asked Git Interview Questions for Software Engineer Roles

100+ QuestionsDetailed AnswersCode ExamplesUpdated for 2026

Introduction

This page provides a comprehensive collection of Git Interview Questions and Answers designed for developers, DevOps engineers, system administrators, and software engineers preparing for technical interviews. Git is a distributed version control system that tracks changes in source code during software development. It allows multiple developers to collaborate efficiently, maintain code history, and manage project versions with ease. This interview guide covers beginner, intermediate, and advanced Git concepts including basic commands, branching, merging, rebasing, workflows, conflict resolution, hooks, submodules, performance optimization, and real-world collaboration scenarios.

Why Git?

  • Industry standard – used by millions of developers worldwide
  • Distributed architecture – every copy is a full repository, enabling offline work and redundancy
  • Powerful branching and merging – lightweight branches and flexible merge strategies
  • Rich ecosystem – integrates with GitHub, GitLab, Bitbucket, and countless CI/CD tools
  • Essential for DevOps – plays a critical role in continuous integration and deployment pipelines
  • Strong community and support – extensive documentation, tools, and best practices available

Most Asked Git Interview Questions

Beginner
1. What is Git and what are its key features?

Git is a distributed version control system that tracks changes in source code during software development. It allows multiple developers to work on the same project simultaneously.

  • Distributed: Each developer has a full copy of the repository
  • Branching: Lightweight and easy branching
  • Merging: Powerful merge capabilities
  • Staging Area: Index for preparing commits
  • History: Complete project history
bash
# Git Basics
# Initialize a new repository
git init

# Check repository status
git status

# Add files to staging area
git add file.txt
git add .  # Add all files

# Commit changes
git commit -m "Initial commit"

# View commit history
git log
git log --oneline --graph --decorate
Beginner
2. How do you configure Git?

Git configuration is managed through the git config command. Settings can be global, system-wide, or repository-specific.

  • Global: --global flag
  • System: --system flag
  • Local: --local flag (default)
  • User Info: user.name and user.email
  • Editor: core.editor
bash
# Git Configuration
# Set global username and email
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# Set editor
git config --global core.editor "code --wait"

# View all configurations
git config --list

# Set default branch name
git config --global init.defaultBranch main

# Set alias
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.st status
Beginner
3. What are Git branches and how do you use them?

Branches in Git are pointers to commits that allow parallel development. Each branch is an independent line of development.

  • Create Branch: git branch branch-name
  • Switch Branch: git checkout branch-name
  • Create and Switch: git checkout -b branch-name
  • List Branches: git branch
  • Delete Branch: git branch -d branch-name
bash
# Git Branching
# Create a new branch
git branch feature-branch

# Switch to a branch
git checkout feature-branch
git switch feature-branch

# Create and switch in one command
git checkout -b new-feature
git switch -c new-feature

# List all branches
git branch
git branch -a  # List all including remote

# Delete a branch
git branch -d feature-branch  # Safely delete
git branch -D feature-branch  # Force delete
Beginner
4. How does Git merging work?

Git merging combines changes from different branches. It creates a new commit that incorporates changes from the merged branch.

  • Fast-forward Merge: Moves branch pointer forward
  • 3-way Merge: Creates merge commit
  • Merge Conflicts: Occur when changes overlap
  • Merge Strategies: Recursive, ours, theirs
  • Merge Tools: Resolve conflicts visually
bash
# Git Merging
# Merge a branch into current branch
git merge feature-branch

# Merge with no fast-forward
git merge --no-ff feature-branch

# Abort a merge
git merge --abort

# View merge conflicts
git status
git diff

# Resolve conflicts manually
# Edit files to resolve conflicts
git add <resolved-files>
git commit -m "Merge resolved"

# Merge strategy options
git merge -s recursive -X theirs feature-branch
git merge -s recursive -X ours feature-branch
Beginner
5. What is Git rebasing and when should you use it?

Git rebasing rewrites commit history by applying commits from one branch onto another. It creates a linear history.

  • Interactive Rebase: git rebase -i HEAD~n
  • Rebase vs Merge: Linear vs branching history
  • Rebasing Rules: Don't rebase shared branches
  • Conflict Resolution: Resolve during rebase
  • Benefits: Cleaner history, easier to follow
bash
# Git Rebasing
# Rebase current branch onto another branch
git rebase main

# Interactive rebase
git rebase -i HEAD~5

# Rebase with merge conflicts
git rebase --continue  # After resolving conflicts
git rebase --skip      # Skip conflicting commit
git rebase --abort     # Abort rebase

# Rebase against specific commit
git rebase --onto main feature-branch

# Rebase preserve merges
git rebase -p main
Beginner
6. What is Git stash and how do you use it?

Git stash temporarily saves uncommitted changes, allowing you to switch branches or pull updates without committing incomplete work.

  • Stash Changes: git stash
  • List Stashes: git stash list
  • Apply Stash: git stash apply
  • Pop Stash: git stash pop
  • Drop Stash: git stash drop
bash
# Git Stashing
# Save uncommitted changes
git stash
git stash push -m "WIP: feature implementation"

# List all stashes
git stash list

# Apply stash (keep stash)
git stash apply
git stash apply stash@{1}

# Apply stash and drop it
git stash pop
git stash pop stash@{1}

# Show stash contents
git stash show -p stash@{0}

# Drop a stash
git stash drop stash@{0}

# Clear all stashes
git stash clear
Beginner
7. How do Git remotes work?

Git remotes are references to remote repositories. They allow collaboration by pushing and pulling changes between repositories.

  • Add Remote: git remote add origin url
  • View Remotes: git remote -v
  • Fetch: git fetch origin
  • Pull: git pull origin main
  • Push: git push origin main
bash
# Git Remotes
# Add a remote repository
git remote add origin https://github.com/user/repo.git

# View remote repositories
git remote -v

# Remove a remote
git remote remove origin

# Rename a remote
git remote rename origin upstream

# Fetch from remote
git fetch origin
git fetch --all

# Pull from remote
git pull origin main
git pull --rebase origin main

# Push to remote
git push origin main
git push -u origin main
Beginner
8. What is the difference between git reset and git revert?

Git reset moves the branch pointer and modifies the commit history. Git revert creates a new commit that undoes changes, preserving history.

  • Reset: Modifies history
  • Revert: Creates new commit
  • Reset --soft: Keeps changes staged
  • Reset --mixed: Keeps changes unstaged
  • Reset --hard: Discards changes
bash
# Git Reset and Revert
# Soft reset (keep changes staged)
git reset --soft HEAD~1

# Mixed reset (keep changes unstaged)
git reset --mixed HEAD~1
git reset HEAD~1

# Hard reset (discard changes)
git reset --hard HEAD~1

# Revert a commit
git revert HEAD
git revert <commit-hash>

# Revert multiple commits
git revert HEAD~3..HEAD

# Unstage a file
git reset HEAD file.txt
Beginner
9. What is git cherry-pick?

Git cherry-pick applies specific commits from one branch to another. It's useful for selectively merging changes.

  • Single Commit: git cherry-pick commit-hash
  • Multiple Commits: git cherry-pick hash1 hash2
  • Range: git cherry-pick start..end
  • Edit: -e flag to edit commit message
  • No Commit: -n flag to stage changes only
bash
# Git Cherry-Pick
# Cherry-pick a commit
git cherry-pick <commit-hash>

# Cherry-pick multiple commits
git cherry-pick <hash1> <hash2> <hash3>

# Cherry-pick range
git cherry-pick <start-hash>..<end-hash>

# Cherry-pick with edit
git cherry-pick -e <commit-hash>

# Cherry-pick with no commit
git cherry-pick -n <commit-hash>

# Abort cherry-pick
git cherry-pick --abort

# Continue cherry-pick after resolving conflicts
git cherry-pick --continue
Beginner
10. How do you view Git history?

Git log shows commit history with various formatting options for better readability and analysis.

  • Basic Log: git log
  • Oneline: git log --oneline
  • Graph: git log --graph
  • Combined: git log --oneline --graph --decorate
  • Search: git log --grep="pattern"
bash
# Git Log and History
# View commit history
git log
git log --oneline
git log --graph
git log --oneline --graph --decorate

# View log with diff
git log -p
git log -p -2

# Search commits
git log --grep="fix"
git log -S"function_name"

# View commits by author
git log --author="John"

# View commit range
git log HEAD~5..HEAD
git log main..feature

# View commit statistics
git log --stat
git log --shortstat
Intermediate
11. How do you view changes in Git?

Git diff shows differences between commits, branches, or working directory changes. It helps review changes before committing.

  • Unstaged Changes: git diff
  • Staged Changes: git diff --staged
  • Branch Comparison: git diff main..feature
  • Commit Comparison: git diff commit1 commit2
  • Name Only: git diff --name-only
bash
# Git Diff
# Show unstaged changes
git diff

# Show staged changes
git diff --staged
git diff --cached

# Compare branches
git diff main..feature
git diff main...feature  # Compare common ancestor

# Compare commits
git diff <commit1> <commit2>

# Show changed files only
git diff --name-only
git diff --name-status

# Use external diff tool
git difftool

# Ignore whitespace
git diff -w
Intermediate
12. What are Git tags and how do you use them?

Git tags mark specific points in history, typically used for releases. Tags can be lightweight or annotated.

  • Lightweight Tag: git tag v1.0.0
  • Annotated Tag: git tag -a v1.0.0 -m "Release"
  • List Tags: git tag
  • Push Tags: git push origin v1.0.0
  • Delete Tag: git tag -d v1.0.0
bash
# Git Tag
# Create a tag
git tag v1.0.0
git tag -a v1.0.0 -m "Release version 1.0.0"

# Create annotated tag
git tag -a v1.0.0 -m "First release"

# List tags
git tag
git tag -l "v1.*"

# Push tags to remote
git push origin v1.0.0
git push --tags

# Delete a tag
git tag -d v1.0.0
git push origin --delete v1.0.0

# Checkout a tag
git checkout v1.0.0
Intermediate
13. What are Git submodules?

Git submodules allow including other repositories as subdirectories. They maintain references to specific commits in external repositories.

  • Add Submodule: git submodule add url
  • Initialize: git submodule init
  • Update: git submodule update
  • Clone with Submodules: git clone --recursive
  • Status: git submodule status
bash
# Git Submodule
# Add a submodule
git submodule add https://github.com/user/repo.git

# Initialize submodules
git submodule init

# Update submodules
git submodule update
git submodule update --remote

# Clone with submodules
git clone --recursive https://github.com/user/repo.git

# View submodule status
git submodule status

# Remove a submodule
git submodule deinit -f <path>
git rm -f <path>
Intermediate
14. What are Git worktrees?

Git worktrees allow multiple working directories linked to the same repository. They enable simultaneous work on different branches.

  • Create Worktree: git worktree add path branch
  • List Worktrees: git worktree list
  • Remove: git worktree remove path
  • Move: git worktree move old new
  • Prune: git worktree prune
bash
# Git Worktree
# Create a new worktree
git worktree add ../project-feature feature-branch

# Create worktree for new branch
git worktree add -b new-feature ../project-feature main

# List worktrees
git worktree list

# Move worktree
git worktree move ../project-feature ../project-feature-new

# Prune worktrees
git worktree prune

# Remove worktree
git worktree remove ../project-feature
Intermediate
15. What are Git hooks?

Git hooks are scripts that run automatically at specific points in the Git workflow. They enable automation and enforce rules.

  • Pre-commit: Runs before commit
  • Commit-msg: Validates commit messages
  • Pre-push: Runs before pushing
  • Post-commit: Runs after commit
  • Post-receive: Runs on server after push
bash
# Git Hooks
# List all hooks
ls .git/hooks/

# Create a pre-commit hook
# .git/hooks/pre-commit
#!/bin/sh
echo "Running pre-commit hook"
# Add validation script

# Create a commit-msg hook
# .git/hooks/commit-msg
#!/bin/sh
# Validate commit message format

# Create a post-commit hook
# .git/hooks/post-commit
#!/bin/sh
# Run after commit

# Make hooks executable
chmod +x .git/hooks/*

# Skip hooks
git commit --no-verify
Intermediate
16. What is git bisect and how do you use it?

Git bisect uses binary search to find the commit that introduced a bug. It systematically narrows down the problematic commit.

  • Start Bisect: git bisect start
  • Mark Bad: git bisect bad
  • Mark Good: git bisect good commit
  • Test Commit: Check if bug exists
  • Reset: git bisect reset
bash
# Git Bisect
# Start bisect
git bisect start

# Mark current commit as bad
git bisect bad

# Mark known good commit
git bisect good <commit-hash>

# Test and mark commits
git bisect good  # If commit is good
git bisect bad   # If commit is bad

# End bisect
git bisect reset

# Automate bisect
git bisect run ./test-script.sh

# View bisect log
git bisect log
Intermediate
17. What is git blame?

Git blame shows who last modified each line of a file. It's useful for understanding code history and finding responsible authors.

  • Basic Blame: git blame file.txt
  • Line Range: git blame -L 10,20 file.txt
  • Show Commit: git blame -c file.txt
  • Ignore Whitespace: git blame -w
  • Show Email: git blame -e
bash
# Git Blame
# View who changed each line
git blame file.txt

# Show commit details
git blame -c file.txt

# Show line numbers
git blame -L 10,20 file.txt

# Show authors only
git blame -s file.txt

# Show previous commits
git blame file.txt -w  # Ignore whitespace

# View blame for specific commit
git blame <commit-hash> file.txt
Intermediate
18. What is git reflog?

Git reflog records all updates to branch references. It's a safety net for recovering lost commits and undoing mistakes.

  • View Reflog: git reflog
  • Specific Branch: git reflog show main
  • Recover Commit: Checkout reflog entry
  • Expire: Clean old entries
  • Date Format: git reflog --date=iso
bash
# Git Reflog
# View reflog
git reflog

# Show reflog for specific branch
git reflog show main

# Recover lost commit
git reflog
# Find the commit hash
git checkout <commit-hash>

# Create branch from lost commit
git branch recovered-branch <commit-hash>

# Delete reflog entries
git reflog expire --expire=now --all

# Show reflog with dates
git reflog --date=iso
Intermediate
19. What is git clean?

Git clean removes untracked files from the working directory. It helps keep the repository clean and free of unwanted files.

  • Dry Run: git clean -n
  • Remove Files: git clean -f
  • Remove Directories: git clean -fd
  • Interactive: git clean -i
  • Exclude Patterns: git clean -f -e "*.log"
bash
# Git Clean
# Show files to clean
git clean -n
git clean --dry-run

# Remove untracked files
git clean -f
git clean -fd  # Remove directories

# Interactive clean
git clean -i

# Exclude patterns
git clean -f -e "*.log"

# Clean ignored files only
git clean -f -X

# Clean all (including ignored)
git clean -f -x
Intermediate
20. What is git archive?

Git archive creates a tar or zip archive of the repository content. It's useful for creating releases and distributing code.

  • Create Tar: git archive --format=tar main
  • Create Zip: git archive --format=zip main
  • Output File: git archive --output=project.tar main
  • Add Prefix: git archive --prefix=project/ main
  • Specific Directory: git archive main:src/
bash
# Git Archive
# Create a tar archive
git archive --format=tar --output=project.tar main

# Create a zip archive
git archive --format=zip --output=project.zip main

# Archive specific commit
git archive --format=tar --output=project.tar <commit-hash>

# Archive with prefix
git archive --format=tar --prefix=project/ main > project.tar

# Archive specific directory
git archive --format=tar --output=project.tar main:src/
Intermediate
21. What are Git patches?

Git patches are files containing changes that can be shared and applied to other repositories. They enable code review and collaboration.

  • Create Patch: git format-patch -1 commit
  • Apply Patch: git apply patch.diff
  • Apply with Commit: git am patch.diff
  • Generate Patch: git diff > patch.diff
  • Patch Series: Multiple patches in sequence
bash
// Git Patches - Working with diffs and patches
package main

import (
    "fmt"
)

func main() {
    // Git patch commands demonstration
    commands := []string{
        "git format-patch -1 <commit>  # Create a patch from a commit",
        "git apply patch.diff          # Apply a patch without committing",
        "git am patch.diff             # Apply a patch with commit",
        "git diff > patch.diff         # Generate a patch from working directory",
    }
    
    // Patch workflow simulation
    fmt.Println("=== Git Patch Workflow ===")
    for i, cmd := range commands {
        fmt.Printf("%d. %s\n", i+1, cmd)
    }
    
    // Create a simple patch-like diff
    fmt.Println("\n=== Example Patch Format ===")
    patch := `diff --git a/file.txt b/file.txt
index 1234567..abcdefg 100644
--- a/file.txt
+++ b/file.txt
@@ -1,3 +1,4 @@
 Hello World
-This is the old content
+This is the new content
+Added another line
---
2.0.1`
    fmt.Println(patch)
}
Intermediate
22. What is interactive staging in Git?

Interactive staging allows selective staging of changes, enabling granular control over what gets committed.

  • Interactive Add: git add -i
  • Patch Mode: git add -p
  • Interactive Rebase: git rebase -i
  • Interactive Stash: git stash -i
  • Interactive Checkout: git checkout -i
bash
# Git Interactive Add
# Interactive staging
git add -i
git add --interactive

# Add patches interactively
git add -p
git add --patch

# Interactive rebase
git rebase -i HEAD~5

# Interactive stash
git stash -i

# Interactive checkout
git checkout -i
Intermediate
23. What are Git aliases?

Git aliases are shortcuts for Git commands, improving efficiency by reducing typing and remembering complex commands.

  • Create Alias: git config --global alias.co checkout
  • List Aliases: git config --get-regexp alias
  • Remove Alias: git config --global --unset alias.co
  • Complex Aliases: git config --global alias.lg "log --oneline --graph"
  • Shell Aliases: !command for shell commands
bash
# Git Aliases
# Create aliases
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.st status
git config --global alias.ci commit

# Advanced aliases
git config --global alias.lg "log --oneline --graph --decorate"
git config --global alias.unstage "reset HEAD --"

# List aliases
git config --get-regexp alias

# Remove alias
git config --global --unset alias.co

# Alias with multiple commands
git config --global alias.stash-unapply "!git stash show -p | git apply -R"
Intermediate
24. What is .gitignore and how do you use it?

.gitignore specifies intentionally untracked files that Git should ignore. It prevents committing temporary files, build artifacts, and secrets.

  • Create File: .gitignore in repository root
  • Patterns: *.log, node_modules/
  • Negate: !important.log
  • Global: core.excludesfile configuration
  • Check Ignored: git status --ignored
bash
# Git Ignore
# Create .gitignore file
# Ignore specific files
*.log
*.tmp

# Ignore directories
build/
dist/
node_modules/

# Ignore files with pattern
*.~
*.swp

# Ignore specific file
config.env

# ! - Negate pattern
!*.js

# Global .gitignore
git config --global core.excludesfile ~/.gitignore_global

# Check ignored files
git status --ignored
Intermediate
25. What are common Git workflows?

Git workflows define how teams collaborate using Git. Common workflows include feature branching, Git Flow, and GitHub Flow.

  • Feature Branch: Each feature gets a branch
  • Git Flow: Main, develop, feature, release, hotfix
  • GitHub Flow: Main branch with feature branches
  • GitLab Flow: Environment branches
  • Trunk-Based: Short-lived branches
bash
# Git Hooks Examples
# .git/hooks/pre-commit
#!/bin/sh
# Run linter
npm run lint

# .git/hooks/pre-push
#!/bin/sh
# Run tests before push
npm test

# .git/hooks/commit-msg
#!/bin/sh
# Validate commit message
COMMIT_MSG=$(cat $1)
if [ ${#COMMIT_MSG} -lt 10 ]; then
    echo "Commit message too short"
    exit 1
fi

# .git/hooks/pre-rebase
#!/bin/sh
# Prevent rebasing on main branch
if [ "$(git rev-parse --abbrev-ref HEAD)" = "main" ]; then
    echo "Cannot rebase on main branch"
    exit 1
fi
Advanced
26. How do you resolve merge conflicts in Git?

Merge conflicts occur when changes overlap. They must be resolved manually or with merge tools to complete the merge.

  • View Conflicts: git status
  • Conflict Markers: <<<<<<< HEAD, =======, >>>>>>>>
  • Use Merge Tool: git mergetool
  • Accept Changes: git checkout --theirs file
  • Continue Merge: git add and git commit
bash
// Git Merge Conflict Resolution

# Step 1: See the conflict
git status

# Step 2: Open the file and see conflict markers
cat file.txt
# <<<<<<< HEAD
# Current branch changes
# =======
# Incoming branch changes
# >>>>>>> other-branch

# Step 3: Resolve conflicts manually or use merge tool
git mergetool

# Step 4: Accept changes (strategies)
git checkout --ours file.txt    # Keep current branch changes
git checkout --theirs file.txt  # Keep incoming branch changes

# Step 5: Mark as resolved
git add file.txt

# Step 6: Complete the merge
git commit -m "Resolved merge conflicts"
Advanced
27. What is Git squashing?

Git squashing combines multiple commits into a single commit, cleaning up history before merging branches.

  • Interactive Rebase: git rebase -i HEAD~n
  • Squash Action: Replace pick with squash
  • Reset Squash: git reset --soft HEAD~n
  • Merge Squash: git merge --squash
  • Commit Message: Combined message for squashed commits
bash
# Git Cherry-Pick Conflicts
# Start cherry-pick
git cherry-pick <commit-hash>

# View conflicts
git status

# Resolve conflicts in files
# Edit files to resolve

# Add resolved files
git add <resolved-files>

# Continue cherry-pick
git cherry-pick --continue

# Skip commit
git cherry-pick --skip

# Abort cherry-pick
git cherry-pick --abort

# Cherry-pick with strategy
git cherry-pick -X theirs <commit-hash>
git cherry-pick -X ours <commit-hash>
Advanced
28. What is git amend?

Git amend modifies the last commit, allowing changes to the commit message or adding forgotten files.

  • Amend Message: git commit --amend -m "New message"
  • Amend Files: git add then git commit --amend
  • Amend Author: git commit --amend --author="Name <email>"
  • Force Push: git push --force after amend
  • No Edit: git commit --amend --no-edit
bash
// Git Amend - Modifying the Last Commit

# Original commit
git commit -m "Initial commit with bugs"

# Fix a file and amend
echo "Fixing bug" >> file.txt
git add file.txt
git commit --amend --no-edit

# Or change the message
git commit --amend -m "Initial commit with fixed bugs"

# Change author
git commit --amend --author="John Doe <john@email.com>"

# Force push after amend (if already pushed)
git push --force origin main
Advanced
29. What is Git LFS (Large File Storage)?

Git LFS replaces large files with text pointers, storing the actual files on a remote server. It optimizes repository size and performance.

  • Install: git lfs install
  • Track Patterns: git lfs track "*.psd"
  • View Tracked: git lfs track
  • Push LFS: git lfs push origin main
  • Pull LFS: git lfs pull
bash
# Git Advanced Commands
# Find commit by content
git log -S"functionName"

# Find commit by path
git log -- path/to/file

# Show changes in a commit
git show <commit-hash>

# Show commit count
git rev-list --count main

# Show contribution stats
git shortlog -sn

# Show branch divergence
git rev-list --count main..feature

# List all files in a commit
git ls-tree -r main

# Show object details
git cat-file -p <object-hash>
Advanced
30. What is git subtree?

Git subtree manages external dependencies as subdirectories, unlike submodules which use references to external repositories.

  • Add Subtree: git subtree add --prefix=path url branch
  • Pull Updates: git subtree pull --prefix=path url branch
  • Push Changes: git subtree push --prefix=path url branch
  • Split Subtree: git subtree split --prefix=path -b branch
  • Merge Updates: git subtree merge --prefix=path url branch
bash
# Git Troubleshooting
# Fix detached HEAD
git checkout main
git branch -d temp-branch

# Recover deleted file
git checkout HEAD -- file.txt
git checkout <commit-hash> -- file.txt

# Fix wrong commit message
git commit --amend -m "New message"

# Fix wrong author
git commit --amend --author="John Doe <john@email.com>"

# Undo git add
git reset HEAD file.txt

# Remove file from tracking
git rm --cached file.txt

# Find large files
git rev-list --objects --all | git cat-file --batch-check
Advanced
31. What are Git attributes?

Git attributes define per-file settings for diff, merge, and other operations. They are configured in .gitattributes files.

  • Diff Settings: *.txt diff
  • Binary Files: *.png binary
  • Line Endings: *.js text eol=lf
  • Language Detection: *.js linguist-language=JavaScript
  • Export Ignore: test/ export-ignore
bash
# Git Fork and Pull Requests
# Fork repository on GitHub
# Clone your fork
git clone https://github.com/your-username/repo.git

# Add upstream remote
git remote add upstream https://github.com/original-owner/repo.git

# Sync fork with upstream
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

# Create feature branch
git checkout -b feature/new-feature
# Work on feature
git push origin feature/new-feature

# Create pull request on GitHub
# After PR is merged
git checkout main
git pull upstream main
git push origin main
Advanced
32. What is git filter-branch?

Git filter-branch rewrites history by applying filters to commits. It's used for removing sensitive data or rewriting history.

  • Remove File: git filter-branch --tree-filter 'rm -f file.txt' HEAD
  • Replace Email: git filter-branch --env-filter '...' HEAD
  • Remove Folder: git filter-branch --tree-filter 'rm -rf folder' HEAD
  • Cleanup: git reflog expire and git gc
  • Modern Alternative: git filter-repo
bash
# Git Squash Commits
# Squash last 3 commits
git rebase -i HEAD~3
# Replace "pick" with "squash" or "s" for commits to squash

# Squash using reset
git reset --soft HEAD~3
git commit -m "Combined commit message"

# Squash with merge
git merge --squash feature-branch
git commit -m "Squashed feature commit"

# Squash commits in a branch
git checkout feature-branch
git rebase -i main
# Squash commits as needed
Advanced
33. What is git garbage collection?

Git garbage collection cleans up unnecessary files and compresses objects to optimize repository performance.

  • Run GC: git gc
  • Aggressive: git gc --aggressive
  • Prune Now: git gc --prune=now
  • Auto GC: git gc --auto
  • Check Size: git count-objects -v
bash
# Git Amend Commit
# Modify last commit message
git commit --amend -m "New commit message"

# Add files to last commit
git add forgotten-file.txt
git commit --amend --no-edit

# Change commit author
git commit --amend --author="John Doe <john@email.com>"

# Amend and change date
git commit --amend --date="2024-01-01"

# Avoid changing commit message
git add .
git commit --amend --no-edit

# Force push amended commit
git push --force origin main
Advanced
34. How do you set up a Git server?

Git server setup involves creating a bare repository and configuring SSH access for team collaboration.

  • Bare Repository: git init --bare project.git
  • Clone from Server: git clone user@server:/path/to/project.git
  • Add Remote: git remote add origin user@server:/path/to/project.git
  • SSH Access: Add users to git group
  • Permissions: chown -R git:git /path/to/project.git
bash
# Git Hooks - Pre-commit Examples
# .git/hooks/pre-commit
#!/bin/sh

# Run ESLint
echo "Running ESLint..."
npm run lint || exit 1

# Run Tests
echo "Running tests..."
npm test || exit 1

# Check for debugger statements
if grep -r "debugger" src/; then
    echo "Found debugger statements"
    exit 1
fi

# Check for console.log
if grep -r "console.log" src/; then
    echo "Found console.log statements"
    exit 1
fi

# Run formatter
npm run format

# Add formatted files
git add .
Advanced
35. What are Git pre-commit hooks examples?

Pre-commit hooks run before commits, enabling code quality checks, linting, and validation.

  • Lint Check: Run linter before commit
  • Test Run: Execute tests
  • Format Code: Auto-format code
  • Debug Check: Prevent debugger statements
  • Console Check: Prevent console.log statements
bash
# Git LFS (Large File Storage)
# Install Git LFS
git lfs install

# Track large files
git lfs track "*.psd"
git lfs track "*.zip"
git lfs track "*.mp4"

# View tracked files
git lfs track

# Migrate existing files
git lfs migrate import --include="*.psd,*.zip"

# Push LFS files
git push origin main

# Pull LFS files
git lfs pull

# Check LFS status
git lfs status

# View LFS files
git lfs ls-files
Advanced
36. What is git worktree example?

Git worktree allows working on multiple branches simultaneously in separate directories.

  • Create Worktree: git worktree add ../hotfix hotfix-branch
  • Work on Branch: Navigate to worktree directory
  • Make Changes: Edit files and commit
  • Push Changes: git push origin hotfix-branch
  • Remove Worktree: git worktree remove ../hotfix
bash
# Git Subtree
# Add a subtree
git subtree add --prefix=sub/dir https://github.com/user/repo.git main

# Pull updates
git subtree pull --prefix=sub/dir https://github.com/user/repo.git main

# Push changes back
git subtree push --prefix=sub/dir https://github.com/user/repo.git main

# Split subtree
git subtree split --prefix=sub/dir -b subtree-branch

# Merge subtree changes
git subtree merge --prefix=sub/dir -m "Update subtree" main

# View subtree history
git log --oneline --graph --subdir=sub/dir
Advanced
37. What is git bisect example?

Git bisect uses binary search to find the commit that introduced a bug.

  • Start Bisect: git bisect start
  • Mark Bad: git bisect bad HEAD
  • Mark Good: git bisect good commit
  • Test Commit: Check if bug exists
  • Mark Result: git bisect good or git bisect bad
bash
# Git Attributes
# .gitattributes file
# Set diff for specific files
*.txt diff

# Set merge strategy
*.png binary
*.jpg binary

# Set eol
*.js text eol=lf
*.sh text eol=lf
*.bat text eol=crlf

# Set language
*.js linguist-language=JavaScript
*.rb linguist-language=Ruby

# Export ignore
test/ export-ignore
*.spec.js export-ignore

# Merge driver
*.lock merge=binary
Advanced
38. What is git grep and how do you use it?

Git grep searches for patterns in tracked files, providing a powerful way to find code across the repository.

  • Search Pattern: git grep "functionName"
  • With Context: git grep -C 5 "pattern"
  • File Types: git grep "pattern" -- "*.js"
  • Count: git grep -c "pattern"
  • Line Numbers: git grep -n "pattern"
bash
# Git Filter-Branch
# Remove file from history
git filter-branch --tree-filter 'rm -f passwords.txt' HEAD

# Replace email
git filter-branch --env-filter '
    if [ "$GIT_AUTHOR_EMAIL" = "old@email.com" ]
    then
        export GIT_AUTHOR_EMAIL="new@email.com"
    fi
' HEAD

# Remove folder
git filter-branch --tree-filter 'rm -rf node_modules' HEAD

# Cleanup
git reflog expire --expire=now --all
git gc --prune=now
Advanced
39. What are Git notes?

Git notes add metadata to commits without modifying the commit itself. They're useful for adding comments or tracking information.

  • Add Note: git notes add -m "Note content" commit
  • Show Note: git notes show
  • Edit Note: git notes edit
  • Remove Note: git notes remove
  • Push Notes: git push origin refs/notes/*
bash
# Git Garbage Collection
# Run garbage collection
git gc

# Aggressive garbage collection
git gc --aggressive

# Prune objects
git gc --prune=now

# Auto garbage collection
git gc --auto

# Check repository size
git count-objects -v

# Show large objects
git rev-list --objects --all | git cat-file --batch-check

# Find large files
git rev-list --objects --all | grep -E ".(jpg|png|gif|mp4)"
Advanced
40. What are Git aliases advanced examples?

Advanced Git aliases combine multiple commands or use shell scripting for complex operations.

  • Custom Log: git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset - %s'"
  • Short Status: git config --global alias.s "status -s"
  • Amend: git config --global alias.amend "commit --amend --no-edit"
  • Undo: git config --global alias.undo "reset --soft HEAD^"
  • Cleanup: git config --global alias.cleanup "!git branch --merged | grep -v '\\*' | xargs git branch -d"
bash
# Git Server Setup
# Initialize bare repository
git init --bare project.git

# Clone from server
git clone user@server:/path/to/project.git

# Add remote
git remote add origin user@server:/path/to/project.git

# Push to server
git push origin main

# Setup git server with SSH
# Add users to git group
sudo usermod -a -G git user1
sudo usermod -a -G git user2

# Change permissions
chown -R git:git /path/to/project.git
chmod -R 755 /path/to/project.git
Advanced
41. What is git commit-msg hook?

Commit-msg hooks validate commit messages before they are recorded, enforcing standards and formats.

  • Length Check: Minimum and maximum message length
  • Format Check: Type: subject format
  • Issue Reference: Check for issue tracker references
  • Imperative Mood: Ensure imperative tense
  • No Trailing Punctuation: Prevent trailing periods
bash
# Git Hooks - Pre-push
# .git/hooks/pre-push
#!/bin/sh

# Run tests
echo "Running tests..."
npm test
if [ $? -ne 0 ]; then
    echo "Tests failed, push aborted"
    exit 1
fi

# Check branch naming
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
if [[ ! $BRANCH_NAME =~ ^(feature|bugfix|hotfix)/ ]]; then
    echo "Branch name must start with feature/, bugfix/, or hotfix/"
    exit 1
fi

# Check commit messages
git log --format=%s -n 5 | while read msg; do
    if [[ ! $msg =~ ^(FEAT|FIX|DOCS|STYLE|REFACTOR|TEST): ]]; then
        echo "Invalid commit message: $msg"
        exit 1
    fi
done
Advanced
42. What is git cherry-pick multiple commits?

Cherry-picking multiple commits allows applying several commits from one branch to another, providing selective merging.

  • Cherry-pick Range: git cherry-pick start..end
  • Multiple Hashes: git cherry-pick hash1 hash2 hash3
  • Cherry-pick Merge: git cherry-pick -m 1 merge-commit
  • With Edit: git cherry-pick -e commit
  • Without Commit: git cherry-pick -n commit
bash
# Git Worktree Example
# Create a worktree for hotfix
git worktree add ../hotfix hotfix-branch

# Navigate to worktree
cd ../hotfix

# Work on hotfix
git add .
git commit -m "Fix critical bug"

# Push changes
git push origin hotfix-branch

# Create worktree for feature
git worktree add -b feature/new-feature ../new-feature main

# List worktrees
git worktree list

# Remove worktree
git worktree remove ../hotfix

# Prune worktrees
git worktree prune
Advanced
43. What is git rebase workflow?

Git rebase workflow maintains a linear history by applying changes from one branch onto another.

  • Rebase Feature: git rebase main
  • Interactive Rebase: git rebase -i HEAD~n
  • Conflict Resolution: Resolve conflicts and continue
  • Skip Commit: git rebase --skip
  • Abort Rebase: git rebase --abort
bash
# Git Bisect Example
# Start bisect
git bisect start

# Mark current as bad
git bisect bad HEAD

# Mark known good commit
git bisect good <commit-hash>

# Test commit
# Build and test
./build.sh
./test.sh

# Mark based on test result
if test_passed; then
    git bisect good
else
    git bisect bad
fi

# Find the commit that introduced the bug
# End bisect
git bisect reset

# Automate with script
git bisect start HEAD <good-commit>
git bisect run ./test-script.sh
git bisect reset
Advanced
44. What are Git merge strategies?

Git merge strategies determine how changes are combined during a merge, with options for different scenarios.

  • Recursive: Default 3-way merge
  • Resolve: 2-way merge
  • Ours: Keep our changes
  • Theirs: Keep their changes
  • Patience: Better for complex merges
bash
# Git Grep
# Search in all files
git grep "functionName"

# Search with context
git grep -C 5 "functionName"

# Search by file type
git grep "functionName" -- "*.js"

# Search only file names
git grep -l "functionName"

# Count occurrences
git grep -c "functionName"

# Search in specific commit
git grep "functionName" <commit-hash>

# Search across branches
git grep "functionName" main..feature

# Ignore case
git grep -i "functionName"

# Show line numbers
git grep -n "functionName"
Advanced
45. What is git remote advanced usage?

Advanced Git remote usage includes multiple remotes, pruning, and advanced fetch/push operations.

  • Show Remote: git remote show origin
  • Prune Remote: git remote prune origin
  • Add Multiple: git remote add upstream url
  • Set URL: git remote set-url origin new-url
  • Delete Remote: git remote remove origin
bash
# Git Notes
# Add a note to commit
git notes add -m "This commit contains security fix"

# Show notes
git notes show

# Edit note
git notes edit

# Remove note
git notes remove

# Show notes with log
git log --show-notes

# List all notes
git notes list

# Push notes
git push origin refs/notes/*

# Fetch notes
git fetch origin refs/notes/*:refs/notes/*

# Merge notes
git notes merge
Advanced
46. What is git tag advanced usage?

Advanced Git tag usage includes signed tags, tag verification, and tag management workflows.

  • Signed Tag: git tag -s v1.0.0 -m "Release"
  • Verify Tag: git tag -v v1.0.0
  • Show Tag: git show v1.0.0
  • Create Branch from Tag: git checkout -b new-branch v1.0.0
  • Delete Remote Tag: git push origin --delete v1.0.0
bash
# Git Alias Advanced
# Alias for custom log
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset - %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

# Alias for status short
git config --global alias.s "status -s"

# Alias for amend
git config --global alias.amend "commit --amend --no-edit"

# Alias for undo
git config --global alias.undo "reset --soft HEAD^"

# Alias for cleanup
git config --global alias.cleanup "!git branch --merged | grep -v '\*' | grep -v main | xargs git branch -d"

# Alias for last commit
git config --global alias.last "log -1 HEAD"

# Alias for changelog
git config --global alias.changelog "log --oneline --decorate --graph --all"

# List all aliases
git config --get-regexp alias
Advanced
47. What is git submodule advanced usage?

Advanced Git submodule usage includes tracking branches, updating submodules, and managing submodule changes.

  • Track Branch: git submodule add -b develop url
  • Update Remote: git submodule update --remote
  • Update All: git submodule update --init --recursive
  • Show Changes: git diff --submodule
  • Remove Submodule: git submodule deinit -f submodule
bash
# Git Hooks - Commit-msg
# .git/hooks/commit-msg
#!/bin/sh

# Get commit message
COMMIT_MSG=$(cat $1)

# Validate length
if [ ${#COMMIT_MSG} -lt 10 ]; then
    echo "Error: Commit message must be at least 10 characters"
    exit 1
fi

# Validate format
if ! echo "$COMMIT_MSG" | grep -qE "^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .+"; then
    echo "Error: Commit message must start with type: subject"
    echo "Example: feat: Add new feature"
    exit 1
fi

# Check for issue reference
if ! echo "$COMMIT_MSG" | grep -qE "([A-Z]+-[0-9]+)"; then
    echo "Warning: No issue reference found"
    # Allow warning but don't fail
fi

exit 0
Advanced
48. What is git post-commit hook?

Post-commit hooks run after a commit is created, enabling notifications, logging, and CI/CD triggers.

  • Log Commit: Record commit information
  • Send Notification: Notify team about new commits
  • Trigger CI/CD: Start build process
  • Update Documentation: Auto-generate docs
  • Email Notification: Send commit emails
bash
# Git Cherry-pick Multiple Commits
# Cherry-pick a range
git cherry-pick feature-branch~3..feature-branch

# Cherry-pick with merge
git cherry-pick -m 1 <merge-commit>

# Cherry-pick with strategy
git cherry-pick -X theirs <commit-hash>

# Cherry-pick multiple specific commits
git cherry-pick <hash1> <hash2> <hash3>

# Cherry-pick with edit
git cherry-pick -e <commit-hash>

# Cherry-pick without commit
git cherry-pick -n <commit-hash>
# Resolve conflicts
git commit -m "Cherry-picked changes"

# Cherry-pick and keep original author
git cherry-pick -x <commit-hash>
Advanced
49. What is git worktree advanced usage?

Advanced Git worktree usage includes locking, repairing, and managing multiple worktrees efficiently.

  • Lock Worktree: git worktree lock path
  • Unlock Worktree: git worktree unlock path
  • Repair Worktree: git worktree repair path
  • List with Details: git worktree list --porcelain
  • Force Remove: git worktree remove -f path
bash
# Git Rebase Workflow
# Rebase feature branch on main
git checkout feature-branch
git rebase main

# Interactive rebase to squash commits
git rebase -i HEAD~5
# Replace "pick" with "squash" for commits to combine

# Rebase with merge conflicts
# Resolve conflicts in files
git add <resolved-files>
git rebase --continue

# Skip conflict commit
git rebase --skip

# Abort rebase
git rebase --abort

# Rebase with execute commands
git rebase -i HEAD~3
# Add exec command after a commit
# exec npm test

# Rebase with force push
git push --force-with-lease origin feature-branch
Advanced
50. What is git grep advanced usage?

Advanced Git grep usage includes searching across branches, complex patterns, and file filtering.

  • Search Branches: git grep "pattern" $(git rev-list --all)
  • Regex Search: git grep -E "function\s+\w+"
  • Context Lines: git grep -B 5 -A 5 "pattern"
  • File Patterns: git grep "pattern" -- "*.js" "*.ts"
  • Exclude Files: git grep "pattern" -- "*.js" ":(exclude)*.test.js"
bash
# Git Merge Strategies
# Fast-forward merge
git merge --ff feature-branch

# No fast-forward merge
git merge --no-ff feature-branch

# Squash merge
git merge --squash feature-branch
git commit -m "Squashed feature"

# Merge with strategy
git merge -s recursive -X ours feature-branch
git merge -s recursive -X theirs feature-branch

# Merge with patience
git merge -s recursive -X patience feature-branch

# Merge with diff-algorithm
git merge -s recursive -X diff-algorithm=histogram feature-branch

# Abort merge
git merge --abort

# View merge details
git log --graph --oneline --decorate
Advanced
51. What is git blame advanced usage?

Advanced Git blame includes ignoring whitespace, showing previous commits, and formatting output.

  • Ignore Whitespace: git blame -w file.txt
  • Show Previous: git blame -f file.txt
  • Show Email: git blame -e file.txt
  • Show Time: git blame -t file.txt
  • Porcelain Format: git blame --porcelain file.txt
bash
# Git Remote Advanced
# Show remote details
git remote show origin

# Prune remote branches
git remote prune origin

# Update remote tracking
git remote update

# Set remote URL
git remote set-url origin git@github.com:user/repo.git

# Add multiple remotes
git remote add upstream git@github.com:original/repo.git
git remote add backup git@github.com:backup/repo.git

# Fetch from specific remote
git fetch upstream

# Push to specific remote
git push upstream main

# Delete remote branch
git push origin --delete branch-name

# Rename remote branch
git branch -m old-name new-name
git push origin -u new-name
git push origin --delete old-name
Advanced
52. What is git bisect advanced usage?

Advanced Git bisect includes using scripts, visualizing, and logging the bisect process.

  • Script Automation: git bisect run ./test.sh
  • Visualize: git bisect visualize
  • Log: git bisect log
  • Skip: git bisect skip
  • Status: git bisect status
bash
# Git Tag Advanced
# Create lightweight tag
git tag v1.0.0

# Create annotated tag
git tag -a v1.0.0 -m "Release version 1.0.0"

# Create signed tag
git tag -s v1.0.0 -m "Signed release"

# List tags matching pattern
git tag -l "v1.*"

# Show tag details
git show v1.0.0

# Verify signed tag
git tag -v v1.0.0

# Delete local tag
git tag -d v1.0.0

# Delete remote tag
git push origin --delete v1.0.0

# Push specific tag
git push origin v1.0.0

# Push all tags
git push --tags

# Create branch from tag
git checkout -b new-branch v1.0.0
Advanced
53. What is git reflog advanced usage?

Advanced Git reflog includes viewing all branches, expiring entries, and formatting output.

  • All Branches: git reflog show --all
  • Date Format: git reflog --date=iso
  • Expire Entries: git reflog expire --expire=90.days.ago
  • Expire Unreachable: git reflog expire --expire-unreachable=now --all
  • Porcelain Format: git reflog --format=porcelain
bash
# Git Submodule Advanced
# Add submodule with specific branch
git submodule add -b develop https://github.com/user/repo.git

# Update submodule to latest
git submodule update --remote

# Update all submodules
git submodule update --init --recursive

# Update submodule to specific commit
cd submodule
git checkout <commit-hash>
cd ..
git add submodule
git commit -m "Update submodule"

# Show submodule changes
git diff --submodule

# Show submodule summary
git submodule summary

# Synchronize submodule URL
git submodule sync

# Remove submodule
git submodule deinit -f submodule
git rm -f submodule
rm -rf .git/modules/submodule
Advanced
54. What is git filter-repo?

Git filter-repo is a modern tool for rewriting history, replacing the older filter-branch with better performance and flexibility.

  • Install: pip install git-filter-repo
  • Remove File: git filter-repo --path file.txt --invert-paths
  • Replace Email: git filter-repo --email-callback '...'
  • Analyze: git filter-repo --analyze
  • Force Push: git push origin --force --all
bash
# Git Hooks - Post-commit
# .git/hooks/post-commit
#!/bin/sh

# Get commit hash
COMMIT_HASH=$(git rev-parse HEAD)

# Log commit
echo "Commit: $COMMIT_HASH" >> .git/commit.log

# Send notification
notify-send "Commit created" "Hash: $COMMIT_HASH"

# Run CI/CD trigger
curl -X POST http://ci-server.com/build -H "Content-Type: application/json" -d "{"commit":"$COMMIT_HASH"}"

# Update documentation
./scripts/update-docs.sh

# Send email notification
echo "Commit $COMMIT_HASH created" | mail -s "New Commit" team@example.com
Advanced
55. What is git sparse checkout?

Git sparse checkout allows checking out only specific files or directories from a repository, reducing disk usage.

  • Enable: git config core.sparseCheckout true
  • Set Patterns: echo "src/" >> .git/info/sparse-checkout
  • Init Sparse: git sparse-checkout init --cone
  • Add Pattern: git sparse-checkout add src/
  • Reapply: git sparse-checkout reapply
bash
// Git Sparse Checkout - Checkout Specific Files/Directories

# Enable sparse checkout
git config core.sparseCheckout true

# Option 1: Using sparse-checkout file (older method)
echo "src/" >> .git/info/sparse-checkout
echo "docs/" >> .git/info/sparse-checkout

# Option 2: Using sparse-checkout command (newer method)
git sparse-checkout init --cone

# Add patterns to include
git sparse-checkout add src/
git sparse-checkout add docs/
git sparse-checkout add README.md

# List currently included patterns
git sparse-checkout list

# Remove a pattern
git sparse-checkout disable

# Reapply sparse checkout patterns
git sparse-checkout reapply

# Example: Only checkout frontend files
git sparse-checkout set frontend/ public/ src/
Advanced
56. What is git partial clone?

Git partial clone downloads only commit history and tree objects, fetching blobs on demand to save bandwidth and disk space.

  • Blobless Clone: git clone --filter=blob:none url
  • Treeless Clone: git clone --filter=tree:0 url
  • Sparse Clone: git clone --filter=blob:none --sparse url
  • Fetch Blobs: git fetch --filter=blob:none
  • Unshallow: git fetch --unshallow
bash
# Git Grep Advanced
# Search with regex
git grep -E "functions+w+"

# Search in all branches
git grep "pattern" $(git rev-list --all)

# Search with count
git grep -c "pattern"

# Search with context lines
git grep -B 5 -A 5 "pattern"

# Search with file patterns
git grep "pattern" -- "*.js" "*.ts"

# Search excluding files
git grep "pattern" -- "*.js" ":(exclude)*.test.js"

# Search with line numbers
git grep -n "pattern"

# Show matching files only
git grep -l "pattern"

# Show non-matching files
git grep -L "pattern"

# Search in specific commit range
git grep "pattern" HEAD~5..HEAD
Advanced
57. What is git shallow clone?

Git shallow clone limits history depth, saving bandwidth and disk space by not downloading the full commit history.

  • Depth 1: git clone --depth 1 url
  • Depth N: git clone --depth 50 url
  • Fetch More: git fetch --depth=100
  • Unshallow: git fetch --unshallow
  • Single Branch: git clone --single-branch --branch main url
bash
# Git Blame Advanced
# Show blame with commit info
git blame -c file.txt

# Show blame with line numbers
git blame -L 10,20 file.txt

# Show blame with email
git blame -e file.txt

# Show blame with time
git blame -t file.txt

# Show blame ignoring whitespace
git blame -w file.txt

# Show blame with previous commits
git blame -f file.txt

# Show blame in porcelain format
git blame --porcelain file.txt

# Show blame for specific revision
git blame <commit-hash> file.txt

# Show blame for multiple files
git blame file1.txt file2.txt

# Show blame with score
git blame -s file.txt
Advanced
58. What is git bundle?

Git bundle packages Git objects into a single file, useful for transferring repositories without network access.

  • Create Bundle: git bundle create repo.bundle --all
  • Verify Bundle: git bundle verify repo.bundle
  • Clone from Bundle: git clone repo.bundle my-repo
  • Fetch from Bundle: git fetch repo.bundle
  • List Heads: git bundle list-heads repo.bundle
bash
# Git Bisect Advanced
# Start bisect with good and bad
git bisect start HEAD <good-commit>

# Bisect with skip
git bisect skip

# Bisect with visual
git bisect visualize

# Bisect with log
git bisect log > bisect.log

# Bisect with script
git bisect run ./test.sh

# Bisect with multiple scripts
git bisect run ./build.sh && ./test.sh

# Bisect with branch
git bisect start
git bisect bad feature-branch
git bisect good main

# End bisect with branch
git bisect reset main

# Show bisect status
git bisect status

# Bisect with custom command
git bisect run git grep -q "error"
Advanced
59. What is git describe?

Git describe finds the most recent tag reachable from a commit and describes the commit relative to that tag.

  • Describe Commit: git describe
  • With Tags: git describe --tags
  • With Abbrev: git describe --abbrev=7
  • With Dirty: git describe --dirty
  • Exact Match: git describe --exact-match
bash
# Git Reflog Advanced
# View reflog for all branches
git reflog show --all

# View reflog with date
git reflog --date=iso

# View reflog with relative date
git reflog --date=relative

# Show reflog entries
git reflog --oneline

# View reflog for specific branch
git reflog show feature-branch

# Delete reflog entries older than 90 days
git reflog expire --expire=90.days.ago

# Delete reflog entries for stale branches
git reflog expire --expire-unreachable=now --all

# Show reflog with graph
git reflog --graph

# View reflog in porcelain format
git reflog --format=porcelain
Advanced
60. What is git shortlog?

Git shortlog summarizes commit history by author, showing commit counts and summaries.

  • Basic Shortlog: git shortlog
  • With Summary: git shortlog -s
  • With Email: git shortlog -e
  • With Count: git shortlog -sn
  • With Date: git shortlog -sn --since="2024-01-01"
bash
# Git Filter-Repo (Modern)
# Install git-filter-repo
pip install git-filter-repo

# Remove file from history
git filter-repo --path file.txt --invert-paths

# Replace email
git filter-repo --email-callback '
    return email if email != "old@email.com" else "new@email.com"
'

# Rename file
git filter-repo --path-rename old.txt:new.txt

# Remove folder
git filter-repo --path node_modules --invert-paths

# Analyze repository
git filter-repo --analyze

# Force push after filtering
git push origin --force --all
Advanced
61. What is git rev-list?

Git rev-list lists commit objects in reverse chronological order, useful for counting commits and analyzing history.

  • List All: git rev-list --all
  • Count Commits: git rev-list --count main
  • Oneline: git rev-list --oneline main
  • With Date: git rev-list --date=iso main
  • With Author: git rev-list --author="John" main
bash
# Git Large File Storage Advanced
# Install LFS
git lfs install

# Track patterns
git lfs track "*.psd" "*.zip" "*.mp4"

# List tracked patterns
git lfs track

# View LFS files
git lfs ls-files

# Migrate existing files
git lfs migrate import --include="*.psd,*.zip"

# Push LFS files
git lfs push origin main

# Pull LFS files
git lfs pull

# Check LFS status
git lfs status

# Clean LFS cache
git lfs clean

# Prune LFS files
git lfs prune

# Verify LFS installation
git lfs version
Advanced
62. What is git name-rev?

Git name-rev finds symbolic names (branches/tags) for given commit hashes, helping identify commits.

  • Name Commit: git name-rev commit-hash
  • With Tags: git name-rev --tags commit-hash
  • Always: git name-rev --always commit-hash
  • Name Only: git name-rev --name-only commit-hash
  • With Stdin: echo commit-hash | git name-rev --stdin
bash
# Git Sparse Checkout
# Enable sparse checkout
git config core.sparseCheckout true

# Set sparse checkout patterns
echo "src/" >> .git/info/sparse-checkout
echo "!src/tests/" >> .git/info/sparse-checkout

# Read sparse checkout patterns
git sparse-checkout init --cone

# Add patterns
git sparse-checkout add src/

# Set patterns
git sparse-checkout set src/ docs/

# Reapply sparse checkout
git sparse-checkout reapply

# List patterns
git sparse-checkout list

# Disable sparse checkout
git config core.sparseCheckout false
Advanced
63. What is git show-ref?

Git show-ref lists references (branches, tags) in a repository, providing a way to examine refs.

  • Show All: git show-ref
  • Heads Only: git show-ref --heads
  • Tags Only: git show-ref --tags
  • Verify: git show-ref --verify refs/heads/main
  • Exclude: git show-ref --exclude-existing
bash
# Git Partial Clone
# Clone with blobless
git clone --filter=blob:none <url>

# Clone with treeless
git clone --filter=tree:0 <url>

# Clone with sparse
git clone --filter=blob:none --sparse <url>

# Fetch blobs on demand
git fetch --filter=blob:none

# Checkout files
git checkout main

# Show partial clone info
git rev-list --objects --all --filter=blob:none

# Deepen shallow clone
git fetch --deepen=100

# Unshallow clone
git fetch --unshallow

# Convert to partial clone
git repack -a -d --write-bitmap-index
Advanced
64. What is git symbolic-ref?

Git symbolic-ref reads and modifies symbolic refs, such as HEAD, which points to the current branch.

  • Read HEAD: git symbolic-ref HEAD
  • Set HEAD: git symbolic-ref HEAD refs/heads/main
  • Short Read: git symbolic-ref --short HEAD
  • Delete: git symbolic-ref -d HEAD
  • With Message: git symbolic-ref -m "Message" HEAD refs/heads/main
bash
# Git Shallow Clone
# Shallow clone with depth
git clone --depth 1 <url>

# Shallow clone with history
git clone --depth 50 <url>

# Fetch more history
git fetch --depth=100

# Unshallow clone
git fetch --unshallow

# Shallow clone with branch
git clone --depth 1 --branch main <url>

# Convert to full clone
git fetch --unshallow

# Check shallow status
git rev-parse --is-shallow-repository

# Fetch with depth
git fetch --depth=50 origin main

# Clone single branch
git clone --single-branch --branch main <url>
Advanced
65. What is git update-ref?

Git update-ref updates the object name stored in a reference, allowing direct manipulation of refs.

  • Update Ref: git update-ref refs/heads/branch commit-hash
  • Delete Ref: git update-ref -d refs/heads/branch
  • With Message: git update-ref -m "Message" refs/heads/branch commit-hash
  • No Deref: git update-ref --no-deref refs/heads/branch commit-hash
  • Stdin: git update-ref --stdin
bash
# Git Bundle
# Create a bundle
git bundle create repo.bundle --all

# Create bundle with specific branch
git bundle create repo.bundle main

# Create bundle with tags
git bundle create repo.bundle --tags

# Verify bundle
git bundle verify repo.bundle

# List bundle contents
git bundle list-heads repo.bundle

# Clone from bundle
git clone repo.bundle my-repo

# Fetch from bundle
git fetch repo.bundle

# Pull from bundle
git pull repo.bundle main

# Create bundle from specific commits
git bundle create repo.bundle HEAD~10..HEAD
Advanced
66. What is git hash-object?

Git hash-object computes the SHA-1 hash of a file and optionally stores it in the object database.

  • Compute Hash: git hash-object file.txt
  • Store Object: git hash-object -w file.txt
  • Store Type: git hash-object -t blob -w file.txt
  • From Stdin: echo "content" | git hash-object -w --stdin
  • No Filters: git hash-object --no-filters file.txt
bash
# Git Describe
# Describe current commit
git describe

# Describe with tags
git describe --tags

# Describe with all refs
git describe --all

# Describe with abbrev
git describe --abbrev=7

# Describe with long format
git describe --long

# Describe with match
git describe --match "v*"

# Describe with dirty marker
git describe --dirty

# Describe for specific commit
git describe <commit-hash>

# Describe with exact match
git describe --exact-match

# Describe with first parent
git describe --first-parent
Advanced
67. What is git cat-file?

Git cat-file displays the contents or type of a Git object, useful for examining the object database.

  • Show Content: git cat-file -p hash
  • Show Type: git cat-file -t hash
  • Show Size: git cat-file -s hash
  • Batch: git cat-file --batch
  • Textconv: git cat-file --textconv file.txt
bash
# Git Shortlog
# Show shortlog
git shortlog

# Show shortlog with summary
git shortlog -s

# Show shortlog with email
git shortlog -e

# Show shortlog with count
git shortlog -sn

# Show shortlog with commit count
git shortlog -sn --all

# Show shortlog with file changes
git shortlog -sn -- -- "*.js"

# Show shortlog by date
git shortlog -sn --since="2024-01-01"

# Show shortlog by author
git shortlog -sn --author="John"

# Show shortlog with number of commits
git shortlog -sn | head -10

# Show shortlog with email and count
git shortlog -sen
Advanced
68. What is git ls-files?

Git ls-files shows information about files in the index and working directory.

  • List Files: git ls-files
  • With Stage: git ls-files --stage
  • With Others: git ls-files --others
  • With Ignored: git ls-files --ignored
  • With Modified: git ls-files --modified
bash
# Git Rev-List
# List all commits
git rev-list --all

# List commits in branch
git rev-list main

# Count commits
git rev-list --count main

# List commits with message
git rev-list --oneline main

# List commits with date
git rev-list --date=iso main

# List commits with author
git rev-list --author="John" main

# List commits with grep
git rev-list --grep="fix" main

# List commits with range
git rev-list main..feature

# List commits with first parent
git rev-list --first-parent main

# List commits with objects
git rev-list --objects main
Advanced
69. What is git ls-tree?

Git ls-tree lists the contents of a tree object, showing files and subdirectories at a given commit.

  • List Tree: git ls-tree HEAD
  • Recursive: git ls-tree -r HEAD
  • With Tree: git ls-tree -t HEAD
  • With Long: git ls-tree -l HEAD
  • Name Only: git ls-tree --name-only HEAD
bash
# Git Name-Rev
# Show commit reference
git name-rev <commit-hash>

# Show with tags
git name-rev --tags <commit-hash>

# Show with refs
git name-rev --refs=refs/heads/* <commit-hash>

# Show with always
git name-rev --always <commit-hash>

# Show with undefined
git name-rev --undefined <commit-hash>

# Show with name-only
git name-rev --name-only <commit-hash>

# Show with stdin
echo <commit-hash> | git name-rev --stdin

# Show with multiple commits
git name-rev <hash1> <hash2> <hash3>

# Show with skip
git name-rev --skip=2 <commit-hash>
Advanced
70. What is git ls-remote?

Git ls-remote lists references in a remote repository without downloading the full repository.

  • List Remote: git ls-remote origin
  • Heads Only: git ls-remote --heads origin
  • Tags Only: git ls-remote --tags origin
  • Specific Ref: git ls-remote origin main
  • With Symref: git ls-remote --symref origin
bash
# Git Show-Ref
# Show all refs
git show-ref

# Show heads
git show-ref --heads

# Show tags
git show-ref --tags

# Show specific ref
git show-ref refs/heads/main

# Show with hash
git show-ref --hash=7

# Show with verify
git show-ref --verify refs/heads/main

# Show with heads and tags
git show-ref --heads --tags

# Show with pattern
git show-ref "*feature*"

# Show with quiet
git show-ref --quiet refs/heads/main

# Show with exclusive
git show-ref --exclude-existing
Advanced
71. What is git diff advanced usage?

Advanced Git diff includes comparing commits, branches, and using various diff options for detailed analysis.

  • Compare Commits: git diff commit1 commit2
  • Compare Branches: git diff main..feature
  • With Stat: git diff --stat
  • With Patch: git diff --patch
  • Ignore Whitespace: git diff -w
bash
# Git Symbolic-Ref
# Read symbolic ref
git symbolic-ref HEAD

# Set symbolic ref
git symbolic-ref HEAD refs/heads/main

# Read short ref
git symbolic-ref --short HEAD

# Read with quiet
git symbolic-ref -q HEAD

# Set with force
git symbolic-ref -f HEAD refs/heads/main

# Read for specific ref
git symbolic-ref refs/remotes/origin/HEAD

# Delete symbolic ref
git symbolic-ref -d HEAD

# Show with message
git symbolic-ref -m "Switch to main" HEAD refs/heads/main

# Read with show-ref
git symbolic-ref --show-ref HEAD
Advanced
72. What is git format-patch?

Git format-patch generates patch files for commits, suitable for email submission and code review.

  • Single Commit: git format-patch -1 commit-hash
  • Range: git format-patch start..end
  • With Subject: git format-patch --subject-prefix="PATCH" HEAD~3
  • With Output: git format-patch -o patches/ HEAD~3
  • With Thread: git format-patch --thread HEAD~3
bash
# Git Update-Ref
# Update ref to commit
git update-ref refs/heads/new-branch <commit-hash>

# Delete ref
git update-ref -d refs/heads/branch-to-delete

# Update ref with message
git update-ref -m "Moving branch" refs/heads/branch <commit-hash>

# Create symbolic ref
git update-ref --stdin
# create refs/heads/new-branch <commit-hash>^0

# Update multiple refs
git update-ref refs/heads/branch1 <hash1>
git update-ref refs/heads/branch2 <hash2>

# Update with force
git update-ref -f refs/heads/branch <commit-hash>

# Update with no deref
git update-ref --no-deref refs/heads/branch <commit-hash>

# Show current ref
git symbolic-ref HEAD
Advanced
73. What is git am?

Git am applies a series of patches from a mailbox, preserving commit information and handling conflicts.

  • Apply Patches: git am patches/*.patch
  • With 3-way: git am -3 patch.diff
  • With Directory: git am --directory=src/ patch.diff
  • With Signoff: git am --signoff patch.diff
  • Continue: git am --continue
bash
# Git Hash-Object
# Compute hash of content
git hash-object file.txt

# Store object in database
git hash-object -w file.txt

# Store with type
git hash-object -t blob -w file.txt

# Store from stdin
echo "content" | git hash-object -w --stdin

# Read object
git cat-file -p <hash>

# Show object type
git cat-file -t <hash>

# Compute hash with path
git hash-object --path=file.txt file.txt

# Compute hash without storing
git hash-object --no-filters file.txt

# Store multiple objects
git hash-object -w file1.txt file2.txt

# Show object in tree
git ls-tree HEAD
Advanced
74. What is git apply?

Git apply applies a patch file to the working directory, useful for applying changes without committing.

  • Apply Patch: git apply patch.diff
  • Check: git apply --check patch.diff
  • Reverse: git apply --reverse patch.diff
  • Ignore Whitespace: git apply --ignore-whitespace patch.diff
  • With Index: git apply --index patch.diff
bash
# Git Cat-File
# Show object content
git cat-file -p <hash>

# Show object type
git cat-file -t <hash>

# Show object size
git cat-file -s <hash>

# Show pretty content
git cat-file -p HEAD

# Show tree content
git cat-file -p HEAD^{tree}

# Show commit content
git cat-file -p HEAD

# Show blob content
git cat-file -p HEAD:file.txt

# Show with batch
git cat-file --batch

# Show with batch-check
git cat-file --batch-check

# Show with textconv
git cat-file --textconv file.txt
Advanced
75. What is git revert advanced usage?

Advanced Git revert includes reverting ranges, using strategies, and handling complex reverts.

  • Revert Commit: git revert commit-hash
  • With Edit: git revert -e commit-hash
  • Without Commit: git revert -n commit-hash
  • With Mainline: git revert -m 1 merge-commit
  • Revert Range: git revert start..end
bash
# Git Ls-Files
# List tracked files
git ls-files

# List with stage
git ls-files --stage

# List with others
git ls-files --others

# List with ignored
git ls-files --ignored

# List with exclude
git ls-files --exclude-standard

# List with modified
git ls-files --modified

# List with deleted
git ls-files --deleted

# List with cached
git ls-files --cached

# List with error
git ls-files --error-unmatch file.txt

# List with full name
git ls-files --full-name
Advanced
76. What is git reset advanced usage?

Advanced Git reset includes various reset modes and handling complex reset scenarios.

  • Soft Reset: git reset --soft HEAD~1
  • Mixed Reset: git reset --mixed HEAD~1
  • Hard Reset: git reset --hard HEAD~1
  • With Merge: git reset --merge HEAD~1
  • With Keep: git reset --keep HEAD~1
bash
# Git Ls-Tree
# List tree contents
git ls-tree HEAD

# List recursively
git ls-tree -r HEAD

# List with tree only
git ls-tree -t HEAD

# List with long format
git ls-tree -l HEAD

# List with name only
git ls-tree --name-only HEAD

# List with full tree
git ls-tree --full-tree HEAD

# List with path
git ls-tree HEAD:src/

# List with object ID
git ls-tree -r HEAD --object-only

# List with commit
git ls-tree HEAD -- src/ docs/

# List with abbrev
git ls-tree --abbrev=7 HEAD
Advanced
77. What is git checkout advanced usage?

Advanced Git checkout includes orphan branches, tracking, and various checkout options.

  • Orphan Branch: git checkout --orphan new-branch
  • Track Remote: git checkout --track origin/feature
  • With Merge: git checkout --merge main
  • With Force: git checkout -f main
  • With Quiet: git checkout -q main
bash
# Git Ls-Remote
# List remote branches
git ls-remote origin

# List remote heads
git ls-remote --heads origin

# List remote tags
git ls-remote --tags origin

# List with refs
git ls-remote origin refs/heads/*

# List with specific ref
git ls-remote origin main

# List with upload-pack
git ls-remote --upload-pack

# List with exit code
git ls-remote --exit-code origin

# List with quiet
git ls-remote --quiet origin

# List with symref
git ls-remote --symref origin

# List with sort
git ls-remote --sort=refname origin
Advanced
78. What is git switch?

Git switch is a modern command for switching branches, introduced as a safer alternative to checkout.

  • Switch Branch: git switch main
  • Create Branch: git switch -c new-branch
  • With Force: git switch -f main
  • With Merge: git switch --merge main
  • With Track: git switch --track origin/feature
bash
# Git Diff Advanced
# Show diff between commits
git diff <commit1> <commit2>

# Show diff between branches
git diff main..feature

# Show diff with 3-dots
git diff main...feature

# Show diff with stat
git diff --stat

# Show diff with patch
git diff --patch

# Show diff with color
git diff --color

# Show diff with ignore spaces
git diff -w

# Show diff with name-only
git diff --name-only

# Show diff with find-copies
git diff -C

# Show diff with find-renames
git diff --find-renames
Advanced
79. What is git restore?

Git restore is a modern command for restoring working tree files, introduced as a safer alternative to checkout.

  • Restore File: git restore file.txt
  • Restore Staged: git restore --staged file.txt
  • From Commit: git restore --source=commit-hash file.txt
  • With Patch: git restore -p file.txt
  • Restore All: git restore .
bash
# Git Format-Patch
# Generate patch for commit
git format-patch -1 <commit-hash>

# Generate patches for range
git format-patch <start>..<end>

# Generate patches with subject
git format-patch --subject-prefix="PATCH" HEAD~3

# Generate patches with output
git format-patch -o patches/ HEAD~3

# Generate patches with number
git format-patch -n HEAD~3

# Generate patches with thread
git format-patch --thread HEAD~3

# Generate patches with cover-letter
git format-patch --cover-letter HEAD~3

# Generate patches for current branch
git format-patch main

# Generate patches for all commits
git format-patch --all

# Generate patches with signoff
git format-patch --signoff HEAD~3
Advanced
80. What is git stash advanced usage?

Advanced Git stash includes stashing with untracked files, keeping index, and applying with options.

  • Stash with Untracked: git stash push -u
  • Stash with All: git stash push -a
  • Stash with Keep-Index: git stash push --keep-index
  • Stash with Patch: git stash push -p
  • Apply with Index: git stash apply --index
bash
# Git Am (Apply Mailbox)
# Apply patch series
git am patches/*.patch

# Apply with 3-way merge
git am -3 patch.diff

# Apply with directory
git am --directory=src/ patch.diff

# Apply with signoff
git am --signoff patch.diff

# Apply with keep
git am --keep patch.diff

# Apply with ignore
git am --ignore-whitespace patch.diff

# Apply with fallback
git am --fallback patch.diff

# Continue after conflict
git am --continue

# Skip patch
git am --skip

# Abort am
git am --abort
Advanced
81. What is git log advanced usage?

Advanced Git log includes formatting, filtering, and custom output options for detailed history analysis.

  • Pretty Format: git log --pretty=format:"%h - %s (%cr) <%an>"
  • With Graph: git log --graph --oneline --decorate
  • With Author: git log --author="John"
  • With Grep: git log --grep="fix"
  • With File: git log -- file.txt
bash
// Git Log Advanced Usage - Formatting and Filtering

# Basic log with formatting
git log --pretty=format:"%h - %s (%cr) <%an>"

# Graph view with decorations
git log --graph --oneline --decorate --all

# Filter by author
git log --author="John Doe"

# Filter by commit message
git log --grep="fix"
git log --grep="feature" --grep="bug" --all-match

# Filter by date range
git log --since="2 weeks ago"
git log --until="2023-01-01"

# Filter by files
git log -- file.txt
git log -- src/ README.md

# Show commit stats
git log --stat
git log --shortstat

# Show diff
git log -p

# Limit number of commits
git log -5

# Custom format with colors
git log --pretty=format:"%C(yellow)%h%Creset - %C(blue)%s%Creset %C(red)%cr%Creset (%an)"
Advanced
82. What is git blame with ignore?

Git blame with ignore ignores specified revisions when determining who changed a line, useful for refactoring commits.

  • Ignore Revisions: git blame -w file.txt
  • Ignore File: git blame --ignore-revs-file=.git-blame-ignore-revs file.txt
  • Previous Revisions: git blame -f file.txt
  • With Email: git blame -e file.txt
  • With Time: git blame -t file.txt
bash
# Git Revert Advanced
# Revert a commit
git revert <commit-hash>

# Revert with edit
git revert -e <commit-hash>

# Revert with no commit
git revert -n <commit-hash>

# Revert with mainline
git revert -m 1 <merge-commit>

# Revert with strategy
git revert --strategy=recursive <commit-hash>

# Revert with strategy options
git revert -X theirs <commit-hash>

# Revert range
git revert <start>..<end>

# Revert with signoff
git revert --signoff <commit-hash>

# Revert with no-edit
git revert --no-edit <commit-hash>

# Continue revert
git revert --continue
Advanced
83. What is git grep with regex?

Git grep with regex uses regular expressions for powerful pattern matching across the repository.

  • Extended Regex: git grep -E "function\s+\w+"
  • Basic Regex: git grep -G "function.*"
  • Fixed Strings: git grep -F "functionName"
  • Perl Regex: git grep -P "function\s+\w+"
  • With Word Boundary: git grep -w "function"
bash
# Git Reset Advanced
# Soft reset
git reset --soft HEAD~1

# Mixed reset
git reset --mixed HEAD~1

# Hard reset
git reset --hard HEAD~1

# Reset to commit
git reset --hard <commit-hash>

# Reset with merge
git reset --merge HEAD~1

# Reset with keep
git reset --keep HEAD~1

# Reset with path
git reset HEAD -- file.txt

# Reset with patch
git reset --patch HEAD

# Reset with quiet
git reset --quiet HEAD~1

# Reset with no-edit
git reset --no-edit HEAD~1
Advanced
84. What is git show advanced usage?

Advanced Git show includes formatting options and displaying specific parts of commits.

  • Show Commit: git show commit-hash
  • With Format: git show --pretty=format:"%h - %s"
  • With Stat: git show --stat
  • With Raw: git show --raw
  • No Patch: git show --no-patch
bash
# Git Checkout Advanced
# Checkout branch
git checkout main

# Checkout commit
git checkout <commit-hash>

# Checkout file
git checkout -- file.txt

# Checkout with patch
git checkout -p HEAD

# Checkout with merge
git checkout --merge main

# Checkout with orphan
git checkout --orphan new-branch

# Checkout with track
git checkout --track origin/feature

# Checkout with force
git checkout -f main

# Checkout with quiet
git checkout -q main

# Checkout with progress
git checkout --progress main
Advanced
85. What is git rev-parse?

Git rev-parse parses revision specifiers and returns object names, useful for scripts and plumbing commands.

  • Parse HEAD: git rev-parse HEAD
  • Short Hash: git rev-parse --short HEAD
  • Branch Name: git rev-parse --abbrev-ref HEAD
  • Git Dir: git rev-parse --git-dir
  • Verify: git rev-parse --verify HEAD
bash
# Git Switch
# Switch branch
git switch main

# Switch with create
git switch -c new-branch

# Switch with force
git switch -f main

# Switch with discard
git switch --discard-changes main

# Switch with merge
git switch --merge main

# Switch with progress
git switch --progress main

# Switch with quiet
git switch -q main

# Switch with detach
git switch --detach <commit-hash>

# Switch with orphan
git switch --orphan new-branch

# Switch with track
git switch --track origin/feature
Advanced
86. What is git config advanced usage?

Advanced Git config includes managing multiple configurations and viewing origin information.

  • List All: git config --list
  • With Origin: git config --list --show-origin
  • Get Value: git config user.name
  • Set Value: git config user.name "John Doe"
  • Delete: git config --unset user.name
bash
# Git Restore
# Restore file
git restore file.txt

# Restore staged file
git restore --staged file.txt

# Restore to commit
git restore --source=<commit-hash> file.txt

# Restore with staged
git restore --staged --source=<commit-hash> file.txt

# Restore with worktree
git restore --worktree file.txt

# Restore with checkout
git restore --checkout file.txt

# Restore with merge
git restore --merge file.txt

# Restore with patch
git restore -p file.txt

# Restore multiple files
git restore file1.txt file2.txt

# Restore all files
git restore .
Advanced
87. What is git help?

Git help provides documentation and assistance for Git commands, including guides and tutorials.

  • Help: git help
  • Command Help: git help commit
  • Web Help: git help -w commit
  • Man Help: git help -m commit
  • Tutorial: git help tutorial
bash
# Git Stash Advanced
# Stash with message
git stash push -m "WIP: Feature work"

# Stash with untracked
git stash push -u

# Stash with all
git stash push -a

# Stash with keep-index
git stash push --keep-index

# Stash with path
git stash push -- src/

# Stash with patch
git stash push -p

# Apply stash with index
git stash apply --index

# Apply stash with quiet
git stash apply -q

# Pop stash with index
git stash pop --index

# Show stash with patch
git stash show -p stash@{0}
Advanced
88. What is git instaweb?

Git instaweb starts a web server with Gitweb interface for browsing the repository.

  • Start: git instaweb
  • With Port: git instaweb --port=8080
  • With Browser: git instaweb --browser=firefox
  • Stop: git instaweb --stop
  • Restart: git instaweb --restart
bash
# Git Log Advanced
# Log with graph
git log --graph --oneline --decorate

# Log with pretty format
git log --pretty=format:"%h - %s (%cr) <%an>"

# Log with date format
git log --date=iso

# Log with author
git log --author="John"

# Log with grep
git log --grep="fix"

# Log with file
git log -- file.txt

# Log with full diff
git log -p

# Log with stats
git log --stat

# Log with first parent
git log --first-parent

# Log with range
git log HEAD~5..HEAD
Advanced
89. What is git daemon?

Git daemon provides a simple Git server for anonymous read-only access to repositories.

  • Start Daemon: git daemon
  • With Base Path: git daemon --base-path=/path/to/repos
  • With Port: git daemon --port=9418
  • With Export-All: git daemon --export-all
  • With Verbose: git daemon --verbose
bash
# Git Blame Advanced
# Blame with ignore
git blame -w file.txt

# Blame with previous
git blame -f file.txt

# Blame with email
git blame -e file.txt

# Blame with time
git blame -t file.txt

# Blame with line range
git blame -L 10,20 file.txt

# Blame with reverse
git blame --reverse <commit-hash> file.txt

# Blame with progress
git blame --progress file.txt

# Blame with date format
git blame --date=iso file.txt

# Blame with score
git blame -s file.txt

# Blame with porcelain
git blame --porcelain file.txt
Advanced
90. What is git post-receive hook?

Git post-receive hook runs on the server after a push is received, enabling deployment and notifications.

  • Deploy: Deploy code to production
  • Notify: Send notifications about pushes
  • Build: Trigger build process
  • Test: Run tests on server
  • Log: Log push information
bash
# Git Grep Advanced
# Grep with count
git grep -c pattern

# Grep with name only
git grep -l pattern

# Grep with non-match
git grep -L pattern

# Grep with context
git grep -C 5 pattern

# Grep with before context
git grep -B 5 pattern

# Grep with after context
git grep -A 5 pattern

# Grep with word boundary
git grep -w pattern

# Grep with regex
git grep -E "pattern"

# Grep with ignore case
git grep -i pattern

# Grep with file type
git grep pattern -- "*.js"
Advanced
91. What is git pre-commit advanced hook?

Advanced Git pre-commit hook runs comprehensive checks including linting, formatting, and debugging before commits.

  • Lint Check: Run ESLint or similar
  • Format Check: Auto-format code
  • Debug Check: Check for debugger statements
  • Console Check: Check for console.log
  • Test Run: Run unit tests
bash
# Git Show Advanced
# Show commit
git show <commit-hash>

# Show with format
git show --pretty=format:"%h - %s"

# Show with oneline
git show --oneline

# Show with diff
git show --diff

# Show with stat
git show --stat

# Show with raw
git show --raw

# Show with patch
git show --patch

# Show with no-patch
git show --no-patch

# Show with quiet
git show -q

# Show with abbrev
git show --abbrev-commit
Advanced
92. What are Git advanced workflows?

Git advanced workflows include monorepo management, CI/CD integration, and semantic versioning strategies.

  • Monorepo: Single repository for multiple projects
  • Submodules: Include external dependencies
  • Subtree: Merge external projects
  • CI/CD: Automated testing and deployment
  • Semantic Versioning: Version tagging strategy
bash
# Git Rev-Parse
# Parse revision
git rev-parse HEAD

# Parse short hash
git rev-parse --short HEAD

# Parse branch
git rev-parse --abbrev-ref HEAD

# Parse symbolic ref
git rev-parse --symbolic-full-name HEAD

# Parse git dir
git rev-parse --git-dir

# Parse path
git rev-parse --show-toplevel

# Parse prefix
git rev-parse --show-prefix

# Parse is-inside
git rev-parse --is-inside-work-tree

# Parse is-inside-git-dir
git rev-parse --is-inside-git-dir

# Parse with verify
git rev-parse --verify HEAD
Advanced
93. What is the complete Git workflow?

Complete Git workflow covers the entire development lifecycle from initialization to release.

  • Initialize: git init
  • Feature Development: Create feature branches
  • Code Review: Pull requests and reviews
  • Release: Tag releases
  • Maintenance: Hotfixes and maintenance
bash
# Git Config Advanced
# List all config
git config --list

# List with show-origin
git config --list --show-origin

# Get specific config
git config user.name

# Set config
git config user.name "John Doe"

# Set config global
git config --global user.email "john@email.com"

# Set config local
git config --local core.editor "vim"

# Set config system
git config --system core.editor "vim"

# Delete config
git config --unset user.name

# Delete config global
git config --global --unset user.email

# Edit config
git config --edit
Advanced
94. How do you recover lost commits in Git?

Recovering lost commits uses git reflog to find and restore lost references.

  • View Reflog: git reflog
  • Checkout Commit: git checkout commit-hash
  • Create Branch: git branch recovered-branch commit-hash
  • Reset to Commit: git reset --hard commit-hash
  • Cherry-pick: git cherry-pick commit-hash
bash
# Git Help
# Show help
git help

# Show help for command
git help commit

# Show help with verbose
git help -v

# Show help with guide
git help -g

# Show help with web
git help -w commit

# Show help with info
git help -i commit

# Show help with man
git help -m commit

# Show help with all
git help -a

# Show help with user-manual
git help user-manual

# Show help with tutorial
git help tutorial
Advanced
95. How do you fix detached HEAD in Git?

Detached HEAD occurs when checking out a commit directly. It can be fixed by creating a branch or switching back.

  • Create Branch: git branch new-branch
  • Switch to Branch: git switch new-branch
  • Reset to Branch: git reset --hard main
  • Checkout Branch: git checkout main
  • Merge Changes: git merge <commit-hash>
bash
// Git Detached HEAD - How to Fix

# Scenario: You're in detached HEAD state
# This happens when you checkout a specific commit
git checkout abc1234

# Option 1: Create a new branch from the detached HEAD
git branch new-branch
git checkout new-branch
# Or combine both:
git checkout -b new-branch

# Option 2: Switch back to a branch
git checkout main
# This will show a warning if you have uncommitted changes

# Option 3: Keep changes by creating a branch
git switch -c my-new-branch
git add .
git commit -m "Saved changes from detached HEAD"

# Option 4: Reset to a branch (discard changes)
git reset --hard main

# Option 5: Merge the commit into an existing branch
git checkout main
git merge abc1234

# Option 6: Cherry-pick the commit
git checkout main
git cherry-pick abc1234

# Check current state
git status
git log --oneline
Advanced
96. How do you remove sensitive data from Git history?

Removing sensitive data uses git filter-repo or git filter-branch to rewrite history.

  • Filter-Repo: git filter-repo --path file.txt --invert-paths
  • Filter-Branch: git filter-branch --tree-filter 'rm -f file.txt' HEAD
  • BFG Repo-Cleaner: Alternative tool for cleaning
  • Force Push: git push origin --force --all
  • Cleanup: git reflog expire and git gc
bash
# Git Daemon
# Start git daemon
git daemon

# Start with base-path
git daemon --base-path=/path/to/repos

# Start with port
git daemon --port=9418

# Start with export-all
git daemon --export-all

# Start with verbose
git daemon --verbose

# Start with syslog
git daemon --syslog

# Start with enable
git daemon --enable=receive-pack

# Start with user
git daemon --user=git

# Start with group
git daemon --group=git

# Start with inetd
git daemon --inetd
Advanced
97. How do you resolve Git merge conflicts with command line?

Resolving merge conflicts using command line involves editing files and using Git commands to complete the merge.

  • View Conflicts: git status
  • Edit Files: Resolve conflict markers
  • Add Resolved: git add file.txt
  • Commit Merge: git commit -m "Merge resolved"
  • Abort Merge: git merge --abort
bash
# Git Hooks - Post-Receive
# .git/hooks/post-receive
#!/bin/sh

# Deploy to production
while read oldrev newrev refname; do
    branch=$(git rev-parse --symbolic --abbrev-ref $refname)
    if [ "$branch" = "main" ]; then
        echo "Deploying to production..."
        git --work-tree=/var/www/html checkout -f
        echo "Deployment complete"
        
        # Run post-deploy scripts
        /var/www/html/scripts/post-deploy.sh
        
        # Send notification
        echo "Deployed commit: $newrev" | mail -s "Production Deploy" team@example.com
    fi
done
Advanced
98. How do you optimize a large Git repository?

Optimizing large Git repositories uses GC, LFS, and pruning to reduce size and improve performance.

  • GC: git gc --aggressive
  • LFS: Use Git LFS for large files
  • Prune: git prune
  • Repack: git repack -a -d
  • Sparse Checkout: Checkout only needed files
bash
# Git Hooks - Pre-commit Advanced
# .git/hooks/pre-commit
#!/bin/sh

# Run multiple checks

# Check for trailing whitespace
git diff --cached --check || exit 1

# Run linter
if [ -f package.json ]; then
    npm run lint || exit 1
fi

# Run formatter
if [ -f .prettierrc ]; then
    npm run format
    git add .
fi

# Check for debugger statements
if git diff --cached | grep -E "^+.*debugger"; then
    echo "Found debugger statements"
    exit 1
fi

# Check for console.log
if git diff --cached | grep -E "^+.*console.log"; then
    echo "Found console.log statements"
    exit 1
fi

# Run tests for modified files
if git diff --cached --name-only | grep -E ".(js|ts|py)$" > /dev/null; then
    npm test || exit 1
fi
Advanced
99. How do you use Git with CI/CD?

Git with CI/CD integrates Git with continuous integration and deployment pipelines for automated testing and deployment.

  • GitHub Actions: Automate workflows
  • GitLab CI: Built-in CI/CD
  • Jenkins: Git integration with Jenkins
  • Webhooks: Trigger builds on push
  • Status Checks: Required checks before merge
bash
# Git Advanced Workflows
# Monorepo with Git
# Use submodules for large projects
git submodule add https://github.com/user/lib.git lib/

# Use subtree for better integration
git subtree add --prefix=lib https://github.com/user/lib.git main

# Git with CI/CD
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Run tests
        run: npm test

# Git with semantic versioning
# Use tags for releases
git tag -a v1.0.0 -m "Release version 1.0.0"
git push origin v1.0.0

# Git with conventional commits
# Commit format: type(scope): subject
# Example: feat(auth): Add login feature
# Example: fix(api): Fix user validation
Advanced
100. What is the Complete Git Workflow?

Complete Git Workflow covers the entire development lifecycle from project initialization to production release.

  • Initialize: Create and configure repository
  • Development: Feature branches and commits
  • Code Review: Pull requests and reviews
  • Testing: CI/CD automated testing
  • Release: Tagging and production deployment
bash
# Complete Git Workflow
# Initialize a new repository
mkdir project
cd project
git init

# Create initial structure
echo "# Project" > README.md
mkdir src docs tests
echo "node_modules/" > .gitignore

# Add and commit
git add .
git commit -m "feat: Initial project setup"

# Create feature branch
git checkout -b feature/new-feature

# Work on feature
echo "console.log('Hello World');" > src/main.js
git add src/main.js
git commit -m "feat: Add main.js with hello world"

# Push feature branch
git push origin feature/new-feature

# Create pull request on GitHub
# After PR is approved and merged

# Update main branch
git checkout main
git pull origin main

# Create release tag
git tag -a v1.0.0 -m "Release version 1.0.0"
git push origin v1.0.0

# Create hotfix branch
git checkout -b hotfix/critical-bug main
git add .
git commit -m "fix: Critical bug fix"
git push origin hotfix/critical-bug

# Merge hotfix
git checkout main
git merge --no-ff hotfix/critical-bug
git push origin main

# Clean up branches
git branch -d feature/new-feature
git branch -d hotfix/critical-bug
git push origin --delete feature/new-feature
git push origin --delete hotfix/critical-bug