Git Like a Pro: 10 Things I Regret Not Knowing Earlier
chintanonweb

chintanonweb @chintanonweb

About: As a software engineer, I find joy in turning imaginative ideas into tangible digital experiences. Creating a better world through code is my passion, and I love sharing my vision with others.

Location:
Dwarka, Gujarat, India
Joined:
Aug 25, 2023

Git Like a Pro: 10 Things I Regret Not Knowing Earlier

Publish Date: Nov 22 '24
276 36

10 Git Things I Regret Not Knowing Earlier

Git is a powerful tool for version control, but when you're starting out, it can feel overwhelming. As a beginner, I made many mistakes, but with time, I realized there were essential commands, concepts, and best practices I wished I had learned earlier. In this guide, I’ll walk you through ten crucial Git lessons step by step, breaking them down so any beginner can understand and implement them confidently.

Introduction

Version control systems like Git are indispensable for developers. They allow you to track changes, collaborate effectively, and maintain a clean codebase. However, Git can be tricky to master if you don't know where to start. These ten tips will help you avoid common pitfalls, boost productivity, and give you a clear roadmap from beginner to advanced usage.


1. How to Undo the Last Commit Without Losing Changes?

One of the first things I struggled with was accidentally committing changes too soon. I later learned the magic of git reset.

Example:

Imagine you've added a file (example.txt) and committed it, but realize the commit message is wrong.

git commit -m "wrong message"
Enter fullscreen mode Exit fullscreen mode

To undo the last commit but keep the changes:

git reset --soft HEAD~1
Enter fullscreen mode Exit fullscreen mode

Now, your files are back in the staging area, and you can re-commit with the correct message:

git commit -m "correct message"
Enter fullscreen mode Exit fullscreen mode

2. What Is the Difference Between git reset and git revert?

Beginners often confuse git reset and git revert. Both undo changes, but they work differently.

  • git reset rewinds history and alters it.
  • git revert creates a new commit that undoes changes, preserving history.

Example: Undoing a Commit with git revert

Let’s say you’ve committed changes you want to reverse but keep track of:

git revert <commit-hash>
Enter fullscreen mode Exit fullscreen mode

Git creates a new commit to negate the changes made by the specified commit.


3. How to Fix Merge Conflicts Like a Pro?

Merge conflicts are intimidating for beginners, but they're easy to manage with practice.

Scenario:

You and a teammate edited the same file. When merging, Git flags a conflict.

git merge feature-branch
Enter fullscreen mode Exit fullscreen mode

Git highlights conflicts in the file:

<<<<<<< HEAD
Your changes
=======
Teammate's changes
>>>>>>> feature-branch
Enter fullscreen mode Exit fullscreen mode

Resolve the conflict by editing the file and removing conflict markers. Then:

git add conflicted-file.txt
git commit -m "Resolved merge conflict"
Enter fullscreen mode Exit fullscreen mode

Pro Tip: Use a visual merge tool like git mergetool for easier conflict resolution.


4. Why and How to Use Branches Effectively?

Branches allow you to work on features or fixes without disrupting the main codebase.

Example: Creating and Switching Branches

To create a branch:

git branch feature-branch
Enter fullscreen mode Exit fullscreen mode

Switch to it:

git checkout feature-branch
Enter fullscreen mode Exit fullscreen mode

Or do both in one command:

git checkout -b feature-branch
Enter fullscreen mode Exit fullscreen mode

After finishing work, merge it into the main branch:

git checkout main
git merge feature-branch
Enter fullscreen mode Exit fullscreen mode

5. How to Safely Stash Changes?

Sometimes, you need to switch branches but don’t want to commit your current changes. Stashing saves the day.

Example:

To stash changes:

git stash
Enter fullscreen mode Exit fullscreen mode

Later, when you want to reapply those changes:

git stash pop
Enter fullscreen mode Exit fullscreen mode

Stashing is perfect for temporary changes or experiments.


6. How to Rewrite Commit History Safely?

Rewriting history can be useful for cleaning up messy commits.

Example: Squashing Commits

Suppose you’ve made three commits on your branch:

git log
Enter fullscreen mode Exit fullscreen mode

Output:

commit 1a2b3c4
commit 5d6e7f8
commit 9g0h1i2
Enter fullscreen mode Exit fullscreen mode

To combine them into one:

git rebase -i HEAD~3
Enter fullscreen mode Exit fullscreen mode

Git opens an interactive editor where you can squash commits. Choose squash for the second and third commits, then save. The commits are merged into one.


7. How to Track Changes with git log and git diff?

Understanding your project’s history is vital. Use git log and git diff to investigate.

Example: Viewing Commit History

To see a concise log:

git log --oneline
Enter fullscreen mode Exit fullscreen mode

For detailed logs:

git log --stat
Enter fullscreen mode Exit fullscreen mode

Example: Comparing Changes

To compare unstaged changes:

git diff
Enter fullscreen mode Exit fullscreen mode

To compare staged changes:

git diff --cached
Enter fullscreen mode Exit fullscreen mode

8. How to Use Tags for Versioning?

Tags mark specific commits, often used for versioning in releases.

Example: Creating a Tag

To tag the current commit:

git tag v1.0
Enter fullscreen mode Exit fullscreen mode

Push the tag to the remote repository:

git push origin v1.0
Enter fullscreen mode Exit fullscreen mode

Tags make it easy to identify significant points in your project.


9. How to Clone, Pull, and Push?

Example: Cloning a Repository

To clone a repository:

git clone https://github.com/user/repo.git
Enter fullscreen mode Exit fullscreen mode

Example: Pulling Changes

To fetch and merge changes from the remote repository:

git pull origin main
Enter fullscreen mode Exit fullscreen mode

Example: Pushing Changes

After committing your work locally:

git push origin feature-branch
Enter fullscreen mode Exit fullscreen mode

10. What Is Gitignore and How Does It Work?

A .gitignore file specifies files Git should ignore, preventing unwanted files from being committed.

Example:

Create a .gitignore file and add patterns for files to ignore:

# Ignore node_modules folder
node_modules/

# Ignore environment files
.env
Enter fullscreen mode Exit fullscreen mode

Add and commit the .gitignore file:

git add .gitignore
git commit -m "Add .gitignore"
Enter fullscreen mode Exit fullscreen mode

Additional tips

11. Organizing Branches into Folders for Better Structure

A lesser-known but highly useful feature in Git is the ability to organize your branches into folders. Instead of simply prefixing branch names with terms like feature, you can create a structured directory-like hierarchy for better organization.

Example:

To create feature branches with folder-like organization:

git branch feature/my-branch-name
git branch feature/teammates-branch
Enter fullscreen mode Exit fullscreen mode

When you list branches, they’ll appear grouped together:

git branch
Enter fullscreen mode Exit fullscreen mode

Output:

  feature/my-branch-name
  feature/teammates-branch
Enter fullscreen mode Exit fullscreen mode

This structure makes it easier to manage and navigate a large number of branches, especially in collaborative projects with various teams and feature types.


12. Using git bisect to Find Problematic Commits

When something breaks in your project, identifying the specific commit that introduced the issue can be challenging. Git's bisect tool simplifies this process by performing a binary search through your commit history.

Example: Finding a Bug with git bisect

  1. Start the bisect process:
   git bisect start
Enter fullscreen mode Exit fullscreen mode
  1. Mark the current (broken) commit as bad:
   git bisect bad
Enter fullscreen mode Exit fullscreen mode
  1. Mark the last known good commit:
   git bisect good <commit-hash>
Enter fullscreen mode Exit fullscreen mode

Git will now check out a commit midway between the good and bad commits. Test your code, then tell Git if this commit is good or bad:

  • If bad:
  git bisect bad
Enter fullscreen mode Exit fullscreen mode
  • If good:
  git bisect good
Enter fullscreen mode Exit fullscreen mode

Repeat this until Git identifies the problematic commit.

  1. Once finished, reset the bisect state:
   git bisect reset
Enter fullscreen mode Exit fullscreen mode

13. Why You Should Know About git reflog

Even when mistakes seem irreversible, git reflog can save you. It tracks changes to the HEAD, allowing you to recover commits even after actions like git reset.

Example: Recovering a Reset Commit

Suppose you accidentally reset your branch:

git reset --hard HEAD~1
Enter fullscreen mode Exit fullscreen mode

You realize you need the previous commit. Use git reflog to find its reference:

git reflog
Enter fullscreen mode Exit fullscreen mode

Output:

1a2b3c4 HEAD@{0}: reset: moving to HEAD~1
5d6e7f8 HEAD@{1}: commit: Added new feature
Enter fullscreen mode Exit fullscreen mode

To restore the previous commit:

git checkout 5d6e7f8
Enter fullscreen mode Exit fullscreen mode

14. Semantic Versioning and Semantic Commits

Semantic versioning and commit messages help maintain clarity in your project, especially for releases.

Example: Semantic Versioning

Version numbers follow the format MAJOR.MINOR.PATCH:

  • MAJOR: Breaking changes.
  • MINOR: New features without breaking backward compatibility.
  • PATCH: Bug fixes.

Example: Semantic Commits

Use descriptive prefixes for commit messages:

  • feat: New feature.
  • fix: Bug fix.
  • docs: Documentation changes.
  • style: Code style changes (e.g., formatting).
git commit -m "feat: add user authentication feature"
git commit -m "fix: resolve crash issue on login"
Enter fullscreen mode Exit fullscreen mode

Automating Changelogs

Tools like semantic-release automate changelog generation based on semantic commit messages, streamlining your release process.


These additional tips on branch organization, troubleshooting with git bisect and reflog, and leveraging semantic practices can take your Git mastery to the next level. They ensure cleaner workflows, easier debugging, and consistent project management.


FAQs

Why Is Git Important for Beginners?

Git helps track code changes, collaborate effectively, and manage project versions.

Can I Undo Changes Without Affecting the Remote Repository?

Yes, commands like git reset and git stash help manage local changes safely.

How Can I Practice Git Commands?

Set up a local repository and experiment with real scenarios. Tools like GitHub also offer interactive learning.


Mastering Git is about practice and understanding core concepts. By applying these ten tips, you’ll go from feeling overwhelmed to confidently managing any Git workflow. Dive in, experiment, and don’t fear mistakes—they’re part of the learning process!

Comments 36 total

  • shahin sh
    shahin shNov 22, 2024

    Download Rimini Pro now and experience the latest image enhancement technology!..Rimini pro download link...sites.google.com/view/smshahin820/...
    Image description

  • Peter Wiersig
    Peter WiersigNov 22, 2024

    I always used git commit --amend for fixing commit messages in point 1

    • Itmam Alam
      Itmam AlamNov 25, 2024

      This is the recommended way! Glad you're using it

    • Julien Bertazzo Lambert
      Julien Bertazzo LambertNov 26, 2024

      Love --amend but always run into trouble amending a commit I've already pushed 😭

      • Supportic
        SupporticNov 27, 2024

        if it's already in the origin repo and you amend something, do a force push afterwards
        I would only recommend doing it in your feature branch, not main or develop where multiple people are working.

  • abdel az
    abdel azNov 23, 2024

    Thanks.

    Very informative

  • Derick Florian
    Derick FlorianNov 23, 2024

    Great article. I did not know about git revert! It's a personal preference but I try to avoid git stash and use work trees instead.

  • Jason Brown
    Jason BrownNov 23, 2024

    This is great. For branches though I'm a

    git switch , git switch -c fan.

  • Jason Gutierrez
    Jason GutierrezNov 24, 2024

    One nice little feature that isnt talked about is organizing your branches into "folders". So instead of prefixing your branch name with feature or what have you, you can create a directory for all potential feature branches.
    git branch feature/my-branch-name
    git branch feature/teammates-branch

  • Prasanth Cherukuri
    Prasanth CherukuriNov 24, 2024

    Great Article and nice comments. Thank You!

  • Alex
    AlexNov 24, 2024

    Worth mentioning git bisect tool, it's good for finding which commit broke something.

    git reflog is useful too, can undo even git reset.

    Also, semantic versioning, e.g. when topic applied to commits, like feat for features, fix, have semantic release package, good to generate changelog automatically.

  • Yawn Yoice
    Yawn YoiceNov 25, 2024

    Well done. Concise but clear and useful

  • Jonathan Westman
    Jonathan WestmanNov 25, 2024

    I prefer to git merge --continue for completing a merge instead of writing another commit message in point 3 after adding your files.

    • Vinicius Morais
      Vinicius MoraisNov 26, 2024

      wooooww man, tks for your contribution. i didn't know about this parameter. I always continue with the commit message instead use this command. Will test later

  • coleman corrigan
    coleman corriganNov 26, 2024

    also git merge-base BranchA BranchB useful when you need to find diverging point for branches

  • João Angelo
    João AngeloNov 26, 2024

    Hi chintanonweb,
    Top 5, very nice and helpful !
    Thanks for sharing.

  • Steve Crane
    Steve CraneNov 27, 2024

    I find git worktree useful. We often work on two major branches, and using worktree lets me switch between them without needing to stash work in the other.

  • Julia Vilando
    Julia VilandoNov 27, 2024

    Ohhh

  • Filipe Seabra
    Filipe SeabraNov 27, 2024

    Great article!
    BTW, it seems the flag --soft is not needed in git reset --soft HEAD~1.
    Just git reset HEAD~1 will do the trick, right?

  • mattk
    mattkNov 27, 2024

    No rebase?? That would be my #1

  • Ben Lee
    Ben LeeNov 28, 2024

    Nice job!

  • Sehan Randilu
    Sehan RandiluNov 29, 2024

    Best Programming Codes to Sell
    Get the best programming codes — 5000+ codes to buy or download for free!
    programmingcodesabc2.blogspot.com/

  • Europa Tips
    Europa Tips Nov 29, 2024

    Thank you

  • Zachary Loeber
    Zachary LoeberNov 29, 2024

    Semantic commit/releases are so incredibly cool. Once you start releasing this way you will never want to do it any other way. Remember, as a rule you will need to avoid squashing commits when you get to this level or you will break semantic releases (it concatenates all the commit messages into one string).

Add comment