Git Version Control
Table of Contents
1. Getting Started with Git
Essential commands to set up and start using Git.
git config
Configure Git settings
# Set your username
git config --global user.name "Your Name"
# Set your email
git config --global user.email "your.email@example.com"
# Set default branch name to 'main'
git config --global init.defaultBranch main
# List all configurations
git config --list
git init
Initialize a new Git repository
# Initialize in current directory
git init
# Initialize in a specific directory
git init project-name
git clone
Clone a repository
# Clone via HTTPS
git clone https://github.com/username/repo.git
# Clone via SSH
git clone git@github.com:username/repo.git
# Clone a specific branch
git clone -b branch-name https://github.com/username/repo.git
2. Basic Git Commands
Essential commands for daily Git usage.
git status
Show the working tree status
# Show status
git status
# Short status
git status -s
git add
Add file contents to the index
# Add specific file
git add filename
# Add all files
git add .
# Add all .js files
git add *.js
# Interactive add
git add -p
git commit
Record changes to the repository
# Commit with message
git commit -m "Your commit message"
# Add and commit in one command
git commit -am "Your commit message"
# Amend last commit
git commit --amend -m "New commit message"
# Change author of last commit
git commit --amend --author="Name " --no-edit
3. Branching & Merging
Working with branches and merging changes.
git branch
List, create, or delete branches
# List local branches
git branch
# List all branches (local and remote)
git branch -a
# Create new branch
git branch branch-name
# Delete branch
git branch -d branch-name
# Force delete branch
git branch -D branch-name
git checkout
Switch branches or restore working tree files
# Switch to branch
git checkout branch-name
# Create and switch to new branch
git checkout -b new-branch
# Discard changes in working directory
git checkout -- filename
git merge
Join two or more development histories together
# Merge branch into current branch
git merge branch-name
# Abort merge in progress
git merge --abort
# Create merge commit even if fast-forward is possible
git merge --no-ff branch-name
git rebase
Reapply commits on top of another base tip
# Rebase current branch on top of main
git rebase main
# Interactive rebase (last 3 commits)
git rebase -i HEAD~3
# Continue after resolving conflicts
git rebase --continue
# Skip current patch
git rebase --skip
# Abort rebase
git rebase --abort
4. Working with Remote Repositories
Commands for collaborating with remote repositories.
git fetch
Download objects and refs from another repository
# Fetch from remote
git fetch origin
# Fetch specific branch
git fetch origin branch-name
# Fetch all remotes
git fetch --all
git pull
Fetch from and integrate with another repository or a local branch
# Pull from current branch
git pull
# Pull from specific branch
git pull origin branch-name
# Rebase instead of merge
git pull --rebase origin branch-name
git push
Update remote refs along with associated objects
# Push to remote
git push origin branch-name
# Push and set upstream
git push -u origin branch-name
# Force push (use with caution!)
git push -f origin branch-name
# Delete remote branch
git push origin --delete branch-name
5. Inspection & Comparison
Examining changes and repository history.
git log
Show commit logs
# Show commit history
git log
# Show compact log
git log --oneline
# Show graph
git log --graph --oneline --decorate --all
# Show changes in commits
git log -p
# Show stats
git log --stat
git diff
Show changes between commits, commit and working tree, etc.
# Show unstaged changes
git diff
# Show staged changes
git diff --staged
# Show changes between branches
git diff branch1..branch2
# Show changes in a specific file
git diff path/to/file
git show
Show various types of objects
# Show last commit
git show
# Show specific commit
git show commit-hash
# Show changes in a commit
git show --name-only commit-hash
6. Undoing Changes
How to undo changes at different stages.
git reset
Reset current HEAD to the specified state
# Unstage files (keep changes)
git reset HEAD file
# Reset to specific commit (keep changes in working directory)
git reset commit-hash
# Hard reset (discard all changes)
git reset --hard commit-hash
# Reset to remote branch
git reset --hard origin/branch-name
git revert
Revert some existing commits
# Revert a commit
git revert commit-hash
# Revert without committing
git revert -n commit-hash
git clean
Remove untracked files from the working tree
# Show what would be removed
git clean -n
# Remove untracked files
git clean -f
# Remove untracked directories
git clean -fd
7. Stashing Changes
Temporarily storing changes for later use.
git stash
Stash the changes in a dirty working directory away
# Stash changes
git stash
# Stash with message
git stash save "message"
# List stashes
git stash list
# Apply last stash
git stash apply
# Apply specific stash
git stash apply stash@{n}
# Pop stash (apply and remove)
git stash pop
# Drop stash
git stash drop stash@{n}
# Clear all stashes
git stash clear
8. Advanced Git Topics
Powerful Git features for complex scenarios and advanced usage.
git reflog
Reference logs, or "reflogs", record when the tips of branches and other references were updated in the local repository.
# Show the reflog for the current branch
git reflog
# Show the reflog for a specific reference
git reflog show HEAD
# Show the reflog for all references
git reflog --all
# Recover a lost commit using reflog
git reflog
# Find the commit hash before the mistake
git reset --hard HEAD@{1} # Replace 1 with the appropriate reflog entry
git bisect
Use binary search to find which commit introduced a bug.
# Start bisect session
git bisect start
# Mark current commit as bad
git bisect bad
# Mark a known good commit (e.g., 10 commits ago)
git bisect good HEAD~10
# For each step, test your code then mark as good or bad
# If the current version is good:
git bisect good
# If the current version is bad:
git bisect bad
# When done, reset to the original state
git bisect reset
git worktree
Manage multiple working trees attached to the same repository.
# Create a new worktree for a branch
git worktree add ../feature-branch feature-branch
# List worktrees
git worktree list
# Remove a worktree
git worktree remove ../feature-branch
# Prune worktree information
git worktree prune
git submodule
Manage project dependencies as submodules.
# Add a submodule
git submodule add https://github.com/username/repo.git path/to/submodule
# Clone a repository with submodules
git clone --recurse-submodules https://github.com/username/repo.git
# Update all submodules
git submodule update --init --recursive
# Update a specific submodule
cd path/to/submodule
git pull origin main
git cherry-pick
Apply the changes introduced by some existing commits
# Apply a specific commit
git cherry-pick commit-hash
# Apply multiple commits
git cherry-pick commit1 commit2
# Apply a range of commits
git cherry-pick start-commit..end-commit
git reflog
Manage reflog information
# Show reflog
git reflog
# Show reflog for specific command
git reflog show command
git bisect
Use binary search to find the commit that introduced a bug
# Start bisect
git bisect start
# Mark current commit as bad
git bisect bad
# Mark a known good commit
git bisect good commit-hash
# Run tests after each step
git bisect run test-command
# End bisect
git bisect reset
Git Aliases
Create shortcuts for frequently used commands
# Set up aliases
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
# Create custom command
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
# Example usage:
git co -b new-feature # Instead of git checkout -b new-feature
git st # Instead of git status
git lg # For a pretty log
9. Git Workflows
Common Git workflows for teams and projects.
1. Feature Branch Workflow
The most common workflow for feature development.
# Create and switch to a new feature branch
git checkout -b feature/new-feature
# Make changes and commit
git add .
git commit -m "Implement new feature"
# Push to remote
git push -u origin feature/new-feature
# Create pull request from GitHub/GitLab UI
# After PR is merged, clean up:
git checkout main
git pull
git branch -d feature/new-feature
2. Gitflow Workflow
A robust workflow for managing releases and hotfixes.
# Initialize gitflow in your repository
git flow init
# Start a new feature
git flow feature start MYFEATURE
# Finish a feature (merges into develop)
git flow feature finish MYFEATURE
# Start a release
git flow release start 1.0.0
# Finish a release (merges into main and develop)
git flow release finish 1.0.0
# Start a hotfix
git flow hotfix start 1.0.1
# Finish a hotfix
git flow hotfix finish 1.0.1
3. Forking Workflow
Ideal for open-source projects with multiple contributors.
# Fork the repository on GitHub
# Clone your fork locally
git clone https://github.com/YOUR-USERNAME/REPOSITORY.git
# Add the original repository as 'upstream'
git remote add upstream https://github.com/ORIGINAL-OWNER/REPOSITORY.git
# Fetch changes from upstream
git fetch upstream
# Merge changes from upstream/main into your local main
git checkout main
git merge upstream/main
# Push updates to your fork
git push origin main
# Create a feature branch
git checkout -b my-feature
# Make changes, commit, and push to your fork
git push -u origin my-feature
# Create a pull request from your fork to the original repository
10. Git Best Practices & Tips
1. Commit Guidelines
Commit Message Format
<type>: <subject>
[Optional body]
[Optional footer]
Example:
feat: add user authentication
- Add JWT authentication
- Create user model and controller
- Set up protected routes
Closes #123
Commit Types
- feat: A new feature
- fix: A bug fix
- docs: Documentation only changes
- style: Changes that do not affect the meaning of the code (white-space, formatting, etc.)
- refactor: A code change that neither fixes a bug nor adds a feature
- perf: A code change that improves performance
- test: Adding missing tests or correcting existing tests
- chore: Changes to the build process or auxiliary tools and libraries
Best Practices
- Keep commits small and focused on a single logical change
- Write clear, concise commit messages in the imperative mood
- Use the body to explain what and why vs. how
- Reference issues and pull requests in the footer
- Avoid committing commented-out code
- Don't commit generated files or dependencies
2. Branch Naming Conventions
# Feature branches
feature/feature-name
# Bug fix branches
bugfix/issue-number-description
# Release branches
release/1.0.0
# Hotfix branches
hotfix/urgent-fix
3. Git Hooks
Automate tasks with Git hooks. Hooks are stored in the .git/hooks directory. For team-wide hooks, consider using a tool like Husky or pre-commit.
# List available hook templates
ls /usr/share/git-core/templates/hooks/
# Make a hook executable
chmod +x .git/hooks/pre-commit
Common Git Hooks:
- pre-commit: Runs before commit message is created
- prepare-commit-msg: Runs before commit message editor is launched
- commit-msg: Used to validate commit message
- post-commit: Runs after commit is completed
- pre-push: Runs before pushing to remote
Example pre-commit hook to run tests:
# Pre-commit hook example
#!/bin/sh
# Run tests before allowing commit
npm test
# Pre-push hook example
#!/bin/sh
# Run linter and tests before pushing
npm run lint && npm test
1. Feature Branch Workflow
# Create and switch to new feature branch
git checkout -b feature/awesome-feature
# Make changes and commit
git add .
git commit -m "Implement awesome feature"
# Push to remote
git push -u origin feature/awesome-feature
# Create pull request from GitHub/GitLab UI
# After PR is merged, clean up:
git checkout main
git pull
git branch -d feature/awesome-feature
2. Handling Merge Conflicts
# When you encounter a conflict during merge/pull:
# 1. Open the files with conflicts
# 2. Look for <<<<<<<, =======, and >>>>>>> markers
# 3. Edit the files to resolve conflicts
# 4. Mark as resolved:
git add filename
# Continue with the merge/pull
git merge --continue
# or
git rebase --continue
3. Rewriting History (Before Pushing)
# Interactive rebase (for last 3 commits)
git rebase -i HEAD~3
# In the editor that opens, you can:
# - pick: keep the commit as is
# - reword: edit commit message
# - edit: modify commit content
# - squash: combine with previous commit
# - drop: remove commit
# After rebasing, force push (if already pushed)
git push --force-with-lease