
A Developer's Guide to Git Commands
In modern software development, Git is as essential as the code itself. It’s the industry-standard Version Control System (VCS) that allows developers to track changes, collaborate seamlessly, and manage complex projects without fear of losing work. Whether you’re a beginner just starting your coding journey or a seasoned pro, mastering the core Git commands is a fundamental skill.
This guide provides a comprehensive overview of the most crucial Git commands, organized into logical sections to help you build a solid foundation.
Table of Contents
- 1. Setting Up Your Project
- 2. The Core Workflow: Staging and Committing
- 3. Branching: Parallel Universes for Your Code
- 4. Collaboration: Working with Remote Repositories
- 5. Oops! How to Undo Mistakes
- 6. Lesser-known Git commands
- 7. Frequently Asked Questions (FAQ)
- 8. References
1. Setting Up Your Project
These are the first commands you’ll ever use. They either create a new version-controlled project from scratch or make a local copy of an existing one.
Command | Description |
---|---|
git init | Initializes a new Git repository in your current directory. It creates a hidden .git subdirectory, which contains all the necessary files and metadata for Git to start tracking changes. |
git clone [url] | Creates a local copy of a remote repository hosted on a server like GitHub or GitLab. This is the most common way to download and start working on an existing project. |
git config | Sets your personal configuration details, most importantly your name and email. This information is embedded in every commit you make. The --global flag sets it for every repository on your system. Example: git config --global user.name "Your Name" |
2. The Core Workflow: Staging and Committing
This is the day-to-day cycle of saving your work. It’s a two-step process: first, you choose which changes you want to save (staging), and then you save them with a descriptive message (committing).
Command | Description |
---|---|
git status | Shows the current state of your project. It’s your main dashboard, allowing you to view which files have been modified, which changes are staged, and which files are untracked. |
git add [file] | Adds a file’s changes to the “staging area.” The staging area is like a draft of your next commit. You can add specific files or use git add . to stage all new and modified files at once. |
git diff | Shows the exact changes you’ve made that haven’t been staged yet. You can use git diff --staged to review the changes that are already in the staging area, waiting to be committed. |
git commit -m "..." | Takes everything in the staging area and saves it as a permanent snapshot in your project’s history. The -m flag allows you to write a brief, descriptive commit message explaining what you changed. |
3. Branching: Parallel Universes for Your Code
Branches are one of Git’s most powerful features. They allow you to create an independent line of development to work on a new feature or fix a bug without affecting the main codebase.
Command | Description |
---|---|
git branch | Lists all the branches in your local repository. You can create a new branch by running git branch [new-branch-name] . |
git checkout [branch] | Switches your working directory to the specified branch. This is how you move between different lines of development. You can also use the shortcut git checkout -b [new-branch-name] to create a new branch and immediately switch to it. |
git merge [branch] | Combines the history of a specified branch into your current branch. This is how you integrate the changes from a completed feature branch back into your main branch (e.g., main or master ). |
git rebase [branch] | An alternative to merging. It rewrites your commit history by taking the commits from your current branch and placing them on top of the commits from another branch, resulting in a cleaner, more linear history. |
4. Collaboration: Working with Remote Repositories
These commands are essential for teamwork. They allow you to synchronize your local repository with a shared remote repository.
Command | Description |
---|---|
git remote add [alias] [url] | Connects your local repository to a remote one (like on GitHub). The alias is a nickname for the URL, which is almost always origin by convention. |
git fetch [alias] | Downloads all the branches and commit history from a remote repository but doesn’t change your local working files. This is useful for seeing what others have been working on without merging it yet. |
git pull | Fetches the changes from the remote repository and immediately tries to merge them into your current branch. It’s a combination of git fetch followed by git merge . |
git push [alias] [branch] | Uploads your local branch and all its new commits to the remote repository. This is how you share your work with your team. |
5. Oops! How to Undo Mistakes
It’s inevitable: sometimes you need to undo a change. Git provides powerful tools to revert your project to a previous state safely.
Command | Description |
---|---|
git log | Displays the entire commit history of your current branch, showing each commit’s ID, author, date, and message. |
git reset [file] | Removes a file from the staging area but keeps the actual changes in your working directory. Using git reset --hard [commit-id] is a more destructive command that discards all changes and resets your project to a specific past commit. |
git revert [commit-id] | Creates a brand-new commit that perfectly undoes the changes from a specific previous commit. This is the safest way to undo changes on a shared, public branch because it doesn’t rewrite history. |
git stash | Temporarily shelves your unstaged changes, allowing you to switch branches quickly. You can then use git stash pop to bring those changes back later. |
6. Lesser-known Git commands
Here is a list of powerful, lesser-known Git commands that can give you more control over your repository.
1. git bisect
: The Automatic Bug Hunter
This is arguably one of the most powerful yet underused Git commands, designed to find the exact commit that introduced a bug.
*What it does: It performs an automatic binary search on your commit history. You tell it a “bad” commit where the bug exists and a “good” commit where it doesn’t. Git then checks out a commit in the middle and asks you if it’s good or bad. By repeating this process, the range quickly narrows down until it pinpoints the exact commit that caused the issue.
*Why it’s useful: Instead of manually checking out dozens or hundreds of commits to find a regression, git bisect
automates the entire process, making it incredibly efficient for locating the source of bugs.
*Example in action:
```bash
# Start the process
git bisect start
# Mark the current commit as having the bug
git bisect bad
# Mark a past commit (e.g., a version tag) as not having the bug
git bisect good v1.2.0
# Git checks out a commit in the middle. Test your code, then run:
# git bisect good (if the bug is NOT present)
# or
# git bisect bad (if the bug IS present)
# Keep repeating until Git tells you which commit is the culprit.
# When you're done, reset your HEAD to its original state:
git bisect reset
```
2. git reflog
: Your Safety Net
The reflog (reference log) is a record of every single place the HEAD
of your branches has been. It’s your ultimate safety net for recovering “lost” work.
*What it does: It shows a log of all recent actions, including commits, resets, merges, and checkouts, even if they were on branches that have since been deleted or were part of a history rewrite.
*Why it’s useful: If you ever accidentally delete a branch, perform a git reset --hard
that you regret, or mess up a rebase, the reflog contains the commit hashes you need to restore your work.
*Example in action:
```bash
# View the log of all recent HEAD movements
git reflog
# Output might look like:
# 2a7e8e9 HEAD@{0}: commit: Add new feature
# d8e4a9a HEAD@{1}: reset: moving to d8e4a9a
# f1c5e0a HEAD@{2}: commit: Some other work
# Found the commit you thought you lost? You can get it back:
git checkout 2a7e8e9
# Or create a new branch from it to be safe
git branch recovered-work 2a7e8e9
```
3. git worktree
: Manage Multiple Branches Simultaneously
This command allows you to check out more than one branch at a time in your repository by linking multiple working directories to a single .git
database.
*What it does: It creates a new directory on your machine that is a clean working copy of another branch in your repository. You can have one directory for main
, another for feature-x
, and a third for a hotfix
, all linked to the same repo.
*Why it’s useful: You can work on a complex feature in one terminal window while quickly fixing a bug on the main branch in another, without having to stash your changes or deal with slow context switching. It’s perfect for reviewing pull requests or running tests on one branch while you code on another.
*Example in action:
```bash
# Create a new worktree in a new directory for the ‘hotfix’ branch
git worktree add ../my-repo-hotfix hotfix
# Now you can 'cd ../my-repo-hotfix' and work on that branch.
# Your main repository directory is untouched.
# When you are done, you can remove the worktree
git worktree remove ../my-repo-hotfix
```
4. git shortlog
: A Formatted git log
for Changelogs
This command summarizes the output of git log
into a more readable format, grouped by author.
*What it does: It presents commits grouped by author, making it easy to see who has been working on what. It’s excellent for generating release notes or changelogs.
*Why it’s useful: It provides a clean, high-level overview of contributions, which is much easier to parse than the raw git log
.
*Example in action:
```bash
# Show a summary of commits, grouped by author, with commit counts
git shortlog -s -n
# Output might look like:
# 25 Pashalis Laoutaris
# 12 Jane Doe
# 5 John Smith
# Show commit messages grouped by author
git shortlog
```
5. git blame -C
: Find the True Origin of Code
You probably know git blame
, which shows who last modified each line of a file. But adding the -C
flag makes it much more powerful by tracking where code blocks were moved or copied from.
*What it does: When analyzing a file, git blame -C
will detect if a block of code was copied from another file or moved from elsewhere within the same file. It will then attribute the code to the original author, not the person who moved it.
*Why it’s useful: It helps you find the true origin and context of a piece of code, even after major refactoring. This is crucial for understanding why a certain logic was implemented in the first place.
*Example in action:
bash # Run blame on a file, but also detect code that was copied from other files git blame -C my_source_file.js
These commands go beyond the daily workflow but provide immense value in specific, often critical, situations. Mastering them can genuinely elevate your proficiency with Git.
7. Frequently Asked Questions (FAQ)
Question | Answer |
---|---|
What is the .git directory? | The .git folder is the heart of a Git repository. It’s a hidden directory created when you run git init or git clone . It contains all the metadata for the project, including the entire history of commits, remote repository addresses, and branch information. |
What’s the difference between git fetch and git pull ? | git fetch downloads changes from a remote repository to your local machine but doesn’t automatically integrate them into your working directory. git pull does both: it fetches the changes and then immediately merges them into your current branch. pull is more convenient for quick updates, while fetch is safer as it allows you to review changes before merging. |
What’s the difference between git merge and git rebase ? | Both commands integrate changes from one branch to another, but they do so differently. git merge creates a new “merge commit” that ties the histories of the two branches together, preserving the original context. git rebase rewrites history by moving the commits from your current branch to the tip of the target branch, resulting in a cleaner, linear history. Merging is safer for public, shared branches, while rebasing is often used to clean up a private feature branch before sharing it. |
How can I undo my last commit? | If the commit only exists on your local repository, the safest way is git reset --soft HEAD~1 . This command will undo the commit but keep your changes staged. If you want to discard the changes entirely, you can use git reset --hard HEAD~1 , but be cautious as this is destructive. If the commit has already been pushed to a remote branch, it’s better to use git revert HEAD , which creates a new commit that undoes the changes of the previous one without altering project history. |
What’s the difference between git reset and git revert ? | git reset moves the current branch tip back to a previous commit, effectively rewriting commit history. It’s best used for local changes that haven’t been shared. git revert undoes a specific commit by creating a brand new commit that contains the inverse changes. It’s the safer option for undoing changes on a public or shared branch because it doesn’t alter the existing history. |
How do I resolve a merge conflict? | A merge conflict occurs when Git can’t automatically merge changes. To resolve it, first, run git status to see which files are conflicted. Open the conflicted files in a text editor and look for the conflict markers (<<<<<<< , ======= , >>>>>>> ). You must manually edit the file to keep the desired changes and remove the conflict markers. After resolving all conflicts in the files, use git add to stage the resolved files and then run git commit to finalize the merge. |
8. References
- Top 20 Git Commands with Examples: A Practical Guide - DataCamp
- List of Useful Git Commands - GeeksforGeeks
- Your Go-To Git Commands CheatSheet - Last9
- A Beginner’s Guide to Git: A Comprehensive Cheatsheet of Common Commands - Reddit
- GIT CHEAT SHEET - GitHub Education
- Common Git commands - GitLab Docs
- Basic Git Commands | Atlassian Git Tutorial