Top 25 Git Commands Every Developer Should Know

Master essential Git commands with step-by-step examples, real-world scenarios, and troubleshooting tips for efficient version control and collaboration.

Top 25 Git Commands Every Developer Should Know: A Complete Guide

Git has become the backbone of modern software development, powering collaboration for millions of developers worldwide. Whether you're a beginner just starting your coding journey or an experienced developer looking to refine your version control skills, mastering Git commands is essential for efficient project management and team collaboration.

This comprehensive guide will walk you through the 25 most important Git commands, providing step-by-step explanations, real-world examples, and troubleshooting tips to help you become a Git expert.

What is Git and Why Should You Care?

Git is a distributed version control system that tracks changes in your code, allowing you to collaborate with others, maintain project history, and manage different versions of your software. Unlike centralized systems, Git gives every developer a complete copy of the project history, making it robust and flexible.

Key Benefits of Git:

- Version Control: Track every change in your codebase - Collaboration: Multiple developers can work on the same project simultaneously - Backup: Distributed nature provides natural backup - Branching: Create separate development lines for features - History: Complete audit trail of all changes

Setting Up Git: The Foundation

Before diving into commands, ensure Git is properly configured:

`bash git config --global user.name "Your Name" git config --global user.email "your.email@example.com" git config --global init.defaultBranch main `

The Top 25 Git Commands Every Developer Should Master

1. git init - Starting Your Git Journey

The git init command initializes a new Git repository in your current directory.

Syntax: `bash git init [repository-name] `

Real-world Example: `bash

Initialize a new project

mkdir my-awesome-app cd my-awesome-app git init

Or initialize with a specific name

git init my-project `

What happens behind the scenes: - Creates a hidden .git directory - Sets up the basic repository structure - Establishes the initial branch (usually main or master)

Troubleshooting Tip: If you accidentally initialize Git in the wrong directory, simply delete the .git folder to remove the repository.

2. git clone - Copying Remote Repositories

Clone creates a local copy of a remote repository.

Syntax: `bash git clone [local-directory-name] `

Real-world Examples: `bash

Clone a GitHub repository

git clone https://github.com/facebook/react.git

Clone to a specific directory

git clone https://github.com/vuejs/vue.git my-vue-project

Clone a specific branch

git clone -b development https://github.com/company/project.git `

Pro Tips: - Use SSH URLs for repositories you have write access to - Clone with --depth 1 for large repositories when you don't need full history

3. git add - Staging Your Changes

The git add command stages changes for the next commit.

Syntax: `bash git add `

Real-world Examples: `bash

Add a specific file

git add index.html

Add multiple files

git add index.html style.css script.js

Add all files in current directory

git add .

Add all files with specific extension

git add *.js

Add files interactively

git add -i `

Understanding the Staging Area: The staging area is like a preview of your next commit. It allows you to carefully choose which changes to include.

Troubleshooting: - Use git status to see what's staged - Use git reset to unstage files

4. git commit - Saving Your Progress

Commits create snapshots of your staged changes.

Syntax: `bash git commit -m "commit message" `

Real-world Examples: `bash

Basic commit

git commit -m "Add user authentication feature"

Commit with detailed message

git commit -m "Fix login bug

- Resolve issue with password validation - Add proper error handling - Update unit tests"

Commit all tracked files (skip staging)

git commit -am "Quick fix for typo"

Amend the last commit

git commit --amend -m "Updated commit message" `

Best Practices for Commit Messages: - Use present tense ("Add feature" not "Added feature") - Keep first line under 50 characters - Be descriptive but concise - Reference issue numbers when applicable

5. git status - Checking Your Repository State

Shows the current state of your working directory and staging area.

Syntax: `bash git status `

Example Output: `bash On branch main Your branch is up to date with 'origin/main'.

Changes to be committed: (use "git reset HEAD ..." to unstage) modified: README.md

Changes not staged for commit: (use "git add ..." to update what will be committed) modified: src/app.js

Untracked files: (use "git add ..." to include in what will be committed) config.json `

Pro Tip: Use git status -s for a shorter, more concise output.

6. git log - Exploring Project History

View the commit history of your repository.

Syntax: `bash git log [options] `

Useful Variations: `bash

Basic log

git log

One line per commit

git log --oneline

Graphical representation

git log --graph --oneline --all

Last 5 commits

git log -5

Commits by specific author

git log --author="John Doe"

Commits in date range

git log --since="2023-01-01" --until="2023-12-31"

Show file changes

git log --stat `

7. git diff - Seeing What Changed

Compare changes between commits, branches, or working directory.

Syntax: `bash git diff [options] [commit/branch] `

Real-world Examples: `bash

See unstaged changes

git diff

See staged changes

git diff --staged

Compare two commits

git diff abc123..def456

Compare branches

git diff main..feature-branch

Show changes for specific file

git diff HEAD~1 src/app.js `

8. git branch - Managing Branches

Create, list, and manage branches in your repository.

Syntax: `bash git branch [options] [branch-name] `

Common Operations: `bash

List all branches

git branch

List all branches (including remote)

git branch -a

Create new branch

git branch feature-login

Create and switch to new branch

git branch -b feature-payment

Delete branch

git branch -d feature-completed

Force delete branch

git branch -D feature-abandoned

Rename current branch

git branch -m new-branch-name `

Real-world Branching Strategy: `bash

Feature development workflow

git branch feature-user-profile git checkout feature-user-profile

... make changes ...

git add . git commit -m "Implement user profile page" `

9. git checkout - Switching Contexts

Switch between branches, commits, or restore files.

Syntax: `bash git checkout [branch/commit/file] `

Examples: `bash

Switch to existing branch

git checkout main

Create and switch to new branch

git checkout -b hotfix-security

Switch to specific commit

git checkout abc1234

Restore file from last commit

git checkout HEAD -- filename.txt

Restore file from specific commit

git checkout abc1234 -- src/config.js `

Important: In newer Git versions, git switch and git restore are preferred for branch switching and file restoration respectively.

10. git switch - Modern Branch Switching

A newer, more intuitive command for switching branches.

Syntax: `bash git switch [branch-name] `

Examples: `bash

Switch to existing branch

git switch main

Create and switch to new branch

git switch -c feature-dashboard

Switch to previous branch

git switch - `

11. git merge - Combining Branches

Integrate changes from one branch into another.

Syntax: `bash git merge [branch-name] `

Real-world Merge Workflow: `bash

Switch to target branch

git switch main

Merge feature branch

git merge feature-login

Merge with custom commit message

git merge feature-payment -m "Add payment processing feature" `

Types of Merges: - Fast-forward: When target branch hasn't diverged - Three-way merge: When both branches have new commits - Squash merge: Combine all feature commits into one

Handling Merge Conflicts: `bash

When conflicts occur

git status # See conflicted files

Edit files to resolve conflicts

git add resolved-file.js git commit # Complete the merge `

12. git pull - Fetching and Merging

Download and integrate changes from remote repository.

Syntax: `bash git pull [remote] [branch] `

Examples: `bash

Pull from default remote and branch

git pull

Pull from specific remote and branch

git pull origin main

Pull with rebase instead of merge

git pull --rebase

Pull from different remote

git pull upstream main `

Best Practice: Always pull before pushing to avoid conflicts.

13. git push - Sharing Your Changes

Upload local commits to remote repository.

Syntax: `bash git push [remote] [branch] `

Common Scenarios: `bash

Push to default remote

git push

Push to specific remote and branch

git push origin main

Push new branch to remote

git push -u origin feature-new-ui

Force push (use with caution!)

git push --force

Push all branches

git push --all

Push tags

git push --tags `

Troubleshooting Push Issues: `bash

If push is rejected due to remote changes

git pull --rebase git push

If you need to force push (dangerous!)

git push --force-with-lease # Safer than --force `

14. git fetch - Getting Remote Updates

Download remote changes without merging.

Syntax: `bash git fetch [remote] `

Examples: `bash

Fetch from default remote

git fetch

Fetch from specific remote

git fetch origin

Fetch all remotes

git fetch --all

Fetch and prune deleted branches

git fetch --prune `

Difference between fetch and pull: - git fetch: Downloads changes but doesn't merge - git pull: Downloads and merges changes (fetch + merge)

15. git remote - Managing Remote Repositories

Configure remote repository connections.

Syntax: `bash git remote [command] [options] `

Common Operations: `bash

List remotes

git remote -v

Add new remote

git remote add upstream https://github.com/original/repo.git

Remove remote

git remote remove old-remote

Rename remote

git remote rename origin new-origin

Change remote URL

git remote set-url origin https://github.com/user/repo.git `

Real-world Example - Fork Workflow: `bash

After forking a repository

git clone https://github.com/yourusername/forked-repo.git cd forked-repo git remote add upstream https://github.com/original/repo.git git remote -v # Verify remotes `

16. git stash - Temporary Storage

Temporarily store uncommitted changes.

Syntax: `bash git stash [command] [options] `

Practical Examples: `bash

Stash current changes

git stash

Stash with message

git stash save "Work in progress on user authentication"

List all stashes

git stash list

Apply most recent stash

git stash apply

Apply and remove stash

git stash pop

Apply specific stash

git stash apply stash@{2}

Drop specific stash

git stash drop stash@{1}

Clear all stashes

git stash clear

Stash including untracked files

git stash -u `

Real-world Stash Scenario: `bash

You're working on a feature but need to quickly fix a bug

git stash save "Half-completed user profile feature" git checkout main git checkout -b hotfix-login-bug

... fix the bug ...

git checkout feature-user-profile git stash pop # Resume your work `

17. git reset - Undoing Changes

Move the current branch pointer and optionally modify working directory.

Syntax: `bash git reset [mode] [commit] `

Reset Modes: `bash

Soft reset - keep changes staged

git reset --soft HEAD~1

Mixed reset (default) - keep changes unstaged

git reset HEAD~1

Hard reset - discard all changes

git reset --hard HEAD~1

Reset specific file

git reset HEAD filename.txt `

Dangerous but Useful: `bash

Undo last commit but keep changes

git reset --soft HEAD~1

Completely reset to remote state

git reset --hard origin/main `

⚠️ Warning: --hard reset permanently deletes changes!

18. git revert - Safe Undoing

Create new commits that undo previous commits.

Syntax: `bash git revert [commit-hash] `

Examples: `bash

Revert last commit

git revert HEAD

Revert specific commit

git revert abc1234

Revert multiple commits

git revert HEAD~3..HEAD

Revert without committing

git revert --no-commit abc1234 `

Why use revert instead of reset? - Safe for shared repositories - Maintains project history - Can be easily undone later

19. git tag - Marking Important Points

Create tags to mark specific points in history.

Syntax: `bash git tag [tag-name] [commit] `

Examples: `bash

Create lightweight tag

git tag v1.0.0

Create annotated tag

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

Tag specific commit

git tag v0.9.0 abc1234

List all tags

git tag

Show tag information

git show v1.0.0

Delete tag

git tag -d v1.0.0

Push tags to remote

git push origin --tags `

Semantic Versioning Example: `bash git tag -a v1.2.3 -m "Bug fix release - Fix authentication issue - Improve error handling - Update dependencies" `

20. git rebase - Rewriting History

Reapply commits on top of another base commit.

Syntax: `bash git rebase [base-branch] `

Interactive Rebase: `bash

Rebase last 3 commits interactively

git rebase -i HEAD~3

Rebase feature branch onto main

git checkout feature-branch git rebase main `

Interactive Rebase Options: - pick: Keep commit as is - reword: Change commit message - edit: Stop to amend commit - squash: Combine with previous commit - drop: Remove commit

Real-world Rebase Workflow: `bash

Clean up feature branch before merging

git checkout feature-user-auth git rebase -i HEAD~5 # Clean up last 5 commits git checkout main git merge feature-user-auth # Now a clean merge `

21. git cherry-pick - Selective Commit Application

Apply specific commits from one branch to another.

Syntax: `bash git cherry-pick [commit-hash] `

Examples: `bash

Cherry-pick single commit

git cherry-pick abc1234

Cherry-pick multiple commits

git cherry-pick abc1234 def5678

Cherry-pick range of commits

git cherry-pick abc1234..def5678

Cherry-pick without committing

git cherry-pick --no-commit abc1234 `

Real-world Scenario: `bash

Apply hotfix from main to release branch

git checkout release-1.0 git cherry-pick hotfix-commit-hash git push origin release-1.0 `

22. git clean - Removing Untracked Files

Remove untracked files and directories.

Syntax: `bash git clean [options] `

Safe Cleaning Process: `bash

See what would be removed (dry run)

git clean -n

Remove untracked files

git clean -f

Remove untracked files and directories

git clean -fd

Remove ignored files too

git clean -fx

Interactive cleaning

git clean -i `

23. git blame - Finding Code Authors

Show who last modified each line of a file.

Syntax: `bash git blame [file] `

Examples: `bash

Basic blame

git blame src/app.js

Blame with line numbers

git blame -L 10,20 src/app.js

Blame with email addresses

git blame -e src/app.js

Ignore whitespace changes

git blame -w src/app.js `

Troubleshooting with Blame: Use git blame to understand code history when debugging issues or understanding complex code sections.

24. git show - Displaying Object Information

Show information about Git objects (commits, tags, etc.).

Syntax: `bash git show [object] `

Examples: `bash

Show last commit

git show

Show specific commit

git show abc1234

Show specific file from commit

git show abc1234:src/app.js

Show tag information

git show v1.0.0

Show commit statistics

git show --stat abc1234 `

25. git config - Configuring Git

Configure Git settings at various levels.

Syntax: `bash git config [--global|--local] [setting] [value] `

Essential Configurations: `bash

User information

git config --global user.name "Your Name" git config --global user.email "your.email@example.com"

Default editor

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

Default branch name

git config --global init.defaultBranch main

Aliases for common commands

git config --global alias.co checkout git config --global alias.br branch git config --global alias.ci commit git config --global alias.st status

List all configurations

git config --list

Get specific configuration

git config user.name `

Real-World Project Workflow Examples

Example 1: Feature Development Workflow

`bash

Start new feature

git checkout main git pull origin main git checkout -b feature-user-dashboard

Make changes

echo "Dashboard content" > dashboard.html git add dashboard.html git commit -m "Add user dashboard page"

Push feature branch

git push -u origin feature-user-dashboard

After code review, merge to main

git checkout main git pull origin main git merge feature-user-dashboard git push origin main

Clean up

git branch -d feature-user-dashboard git push origin --delete feature-user-dashboard `

Example 2: Hotfix Workflow

`bash

Critical bug found in production

git checkout main git pull origin main git checkout -b hotfix-login-security

Fix the bug

git add security-fix.js git commit -m "Fix critical security vulnerability in login"

Push hotfix

git push -u origin hotfix-login-security

Merge to main

git checkout main git merge hotfix-login-security git push origin main

Tag the hotfix

git tag -a v1.0.1 -m "Security hotfix" git push origin --tags `

Example 3: Collaborative Development

`bash

Working with team members

git clone https://github.com/team/project.git cd project

Create feature branch

git checkout -b feature-payment-integration

Regular sync with main

git fetch origin git rebase origin/main

Handle conflicts if they arise

Edit conflicted files

git add resolved-files git rebase --continue

Push your changes

git push -u origin feature-payment-integration `

Advanced Git Troubleshooting

Common Problems and Solutions

Problem 1: Merge Conflicts `bash

When you see conflict markers in files

<<<<<<< HEAD Your changes ======= Their changes >>>>>>> branch-name

Resolution process:

1. Edit files to resolve conflicts

2. Remove conflict markers

3. Stage resolved files

git add conflicted-file.js

4. Complete merge

git commit `

Problem 2: Accidentally Committed to Wrong Branch `bash

Move last commit to correct branch

git reset --soft HEAD~1 # Undo commit, keep changes git stash # Stash changes git checkout correct-branch git stash pop # Apply changes git commit # Commit to correct branch `

Problem 3: Need to Change Commit History `bash

Change last commit message

git commit --amend -m "Corrected commit message"

Squash last 3 commits

git rebase -i HEAD~3

Change 'pick' to 'squash' for commits to combine

`

Problem 4: Lost Work `bash

Find lost commits

git reflog

Recover lost commit

git checkout lost-commit-hash git checkout -b recovery-branch `

Problem 5: Large File Issues `bash

Remove large file from history

git filter-branch --force --index-filter \ 'git rm --cached --ignore-unmatch large-file.zip' \ --prune-empty --tag-name-filter cat -- --all `

Git Best Practices and Tips

Commit Best Practices

1. Make atomic commits: Each commit should represent one logical change 2. Write descriptive messages: Future you will thank you 3. Commit frequently: Small, frequent commits are easier to manage 4. Test before committing: Don't break the build

Branch Management

1. Use descriptive branch names: feature/user-authentication vs branch1 2. Keep branches short-lived: Merge frequently to avoid conflicts 3. Delete merged branches: Keep repository clean 4. Use branch protection rules: Require reviews for important branches

Collaboration Guidelines

1. Pull before pushing: Always sync with remote before pushing 2. Use pull requests: Enable code review and discussion 3. Communicate changes: Use clear commit messages and PR descriptions 4. Respect team conventions: Follow established workflows

Performance Tips

1. Use .gitignore: Don't track unnecessary files 2. Shallow clones: Use --depth 1 for large repositories 3. Prune regularly: Remove stale remote branches 4. Use Git LFS: For large binary files

Conclusion

Mastering these 25 Git commands will significantly improve your development workflow and collaboration capabilities. Git is a powerful tool that becomes more intuitive with practice. Start with the basic commands (init, add, commit, push, pull) and gradually incorporate more advanced features like rebasing, cherry-picking, and interactive staging.

Remember that Git's distributed nature means you have a complete backup of your project history locally. Don't be afraid to experiment – you can almost always recover from mistakes using Git's powerful history and recovery features.

The key to Git mastery is consistent practice and understanding the underlying concepts. Each command serves a specific purpose in the version control workflow, and knowing when and how to use them will make you a more effective developer.

Whether you're working on personal projects or collaborating with large teams, these Git commands form the foundation of modern software development. Take time to practice these commands, experiment with different workflows, and don't hesitate to explore Git's extensive documentation for even more advanced features.

Happy coding, and may your commits always be meaningful and your merges conflict-free!

Tags

  • Collaboration
  • Git
  • Programming
  • Version Control
  • developer tools

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Top 25 Git Commands Every Developer Should Know