Mastering Git: Advanced Commands and Concepts for Developers

Thinura Kumarasinghe
13 min readOct 16, 2023

--

Welcome back, intrepid developer! If you’ve just completed our first article on Git commands and GitHub collaboration or if you’re here because you’ve realised that you could use a deeper understanding of Git’s advanced commands and concepts, you’re in the right place. In this second installment of our series, we’re delving into the intricacies of Git, equipping you with the knowledge and skills to master its more advanced commands.

If you’re new to Git or need a refresher on the basics, we encourage you to start with our first article. There, we cover fundamental Git commands and collaboration on GitHub, providing a strong foundation for your journey into the advanced realm.

In this article, we’ll explore the world of advanced Git commands, such as git rebase, git cherry-pick, git stash, and more. These are the tools that can elevate your version control and code management to a whole new level.

But that’s not all. We’ll also tackle the challenge of handling merge conflicts, and we’ll delve into the debate of Git rebase versus merge, helping you understand when and why to choose one over the other.

So, whether you’re here to expand your Git knowledge or are seeking to sharpen your skills, you’re in for an enlightening experience. By the end of this article, you’ll be equipped with the expertise to confidently navigate the intricate world of Git’s advanced commands and concepts. Let’s dive in and become masters of Git! 🚀🌌👨‍💻

Let’s Crank Up the Volume on Git Commands — (Generated using Supermeme.ai)

Mastering Advanced Git Commands: Elevate Your Version Control Game

As you continue your journey into the Git universe, it’s time to unveil some of the advanced commands that can help you navigate complex scenarios and maintain a clean, organized codebase. Let’s delve into git rebase, git cherry-pick, and git stash, uncover their use cases, and learn how to wield them effectively.

1. Git Rebase: Refining Commit History

git rebase is your tool for rewriting commit history and streamlining the timeline of your project. It’s particularly useful when you want to incorporate changes from one branch into another while keeping a linear history.

Use Case — Rebase:

Suppose you have a feature branch (feature-branch) with multiple commits, and you want to bring those changes up to date with the latest changes in the main branch. You’d do this with:

git checkout feature-branch
git rebase main

2. Git Cherry-Pick: Selective Code Adoption

git cherry-pick empowers you to pick and choose specific commits from one branch and apply them to another. This is valuable when you want to include a particular change without merging the entire branch.

Use Case — Cherry-Pick:

Imagine you’re working on a bug fix in a feature branch (bug-fix-branch) and want to apply it to the main branch. You can cherry-pick the commit using:

git checkout main
git cherry-pick <commit-hash>

3. Git Stash: Temporary Storage of Changes

git stash is your lifesaver when you need to set aside unfinished changes temporarily, switch branches, and return to your work later without committing incomplete code.

Use Case — Stash:

Suppose you’re working on a feature but suddenly need to switch to another branch for an urgent bug fix. Stash your changes like this:

git stash save "Work in progress"

4. Git Stash Pop: Retrieving Changes with a Bit of Risk

Git stash pop is like digging through your closet for your favorite hat. When you pop a stash, you’re applying those hidden changes back into your work, but with a twist.

Use Case — Git Stash Pop:

Imagine you stashed away some changes because your boss urgently needed a quick fix for the website, but you forgot what those changes were. Now, you’re using `git stash pop` like this:

git stash pop

It’s like grabbing that hat from your closet, and, oh boy, you find out it’s filled with spaghetti from your last coding session! Git stash pop is a bit like a magic hat trick — sometimes, it’s exactly what you want, and other times, it’s a surprise adventure. Just make sure your code spaghetti doesn’t ruin the whole party!

5. Git Stash Apply: A Safer Hat Trick

Git stash apply is like having a backup hat for your coding adventures. It’s a bit more predictable and cautious compared to its sibling, `git stash pop`.

Use Case — Git Stash Apply:

Picture yourself in the same situation, stashing your changes because your boss urgently needed a quick fix, but you’re a responsible coder. You want to make sure your favorite coding hat remains in perfect condition. So, you use `git stash apply` like this:

git stash apply

It’s like taking your hat from the closet, checking it for any unexpected surprises (no spaghetti in sight), and confidently placing it on your head. You keep the stash safe and sound, just in case your boss comes back with another last-minute request, or if you simply want to switch hats later. Git stash apply is like a safety net for your changes, ensuring your code doesn’t become a tangled mess.

6. Git Interactive Rebase: Surgical History Editing

git rebase -i (interactive rebase) takes rebasing to the next level. It allows you to interactively reorder, squash, edit, or even delete commits, providing fine-grained control over your commit history.

Use Case — Interactive Rebase:

Suppose you’ve made a series of commits in a feature branch (feature-branch) but want to clean up your commit history before merging it into main. You can use interactive rebase to:

  • Squash multiple commits into one for clarity.
  • Reorder commits to improve the logical flow of changes.
  • Edit commit messages to make them more informative.
git rebase -i

7. Git Submodules: Managing Nested Repositories

git submodules allow you to include other Git repositories within your own. This is helpful when your project depends on external codebases and you want to track their versions.

Use Case — Submodules: Imagine your project relies on a specific library hosted in a separate Git repository. You can add it as a submodule to your project, ensuring that you always have the correct version:

git submodule add [repository_url] [path]

8. Git Bisect: Pinpointing Bugs with Precision

git bisect automates the process of finding the commit that introduced a bug. It helps you narrow down the problematic commit by performing a binary search through your commit history.

Use Case — Bisect:

When a bug is reported, and you need to identify when it was introduced, you can use git bisect to systematically test different commits until you pinpoint the culprit:

git bisect start
git bisect bad # Current commit is bad
git bisect good [commit-hash] # Known good commit

These advanced Git commands provide you with even more powerful tools for managing complex version control scenarios. Whether you’re meticulously editing commit histories, incorporating external repositories, or tracking down elusive bugs, Git offers the flexibility and control you need to excel in software development. With these additions to your Git toolkit, you’ll be well-prepared to tackle a wide range of challenges in your coding endeavors. Happy exploring!

Navigating Merge Conflicts: A Comical Guide to Taming the Git Beast

Merge conflicts — the moments in Git where your code suddenly decides it’s time to throw a little digital tantrum. But worry not, for we’re here to guide you through this tumultuous territory, armed with humor, professionalism, and a dash of whimsy.

What’s a Merge Conflict, Anyway?

Imagine two code wizards (or developers, in our world) are toiling away on the same project. Both of them rush to change the same line of code at the same time. It’s like a spaghetti-tangle of ideas in Git’s mind. That’s a merge conflict, a showdown where Git’s diplomatic skills need a little nudge.

Step 1: The Scene of the Conflict

You’re working on a feature branch and want to merge it into your main branch, but lo and behold, Git lets you know that there's a merge conflict! You'll see something like this:

<<<<<<< HEAD
This is the updated code from the main branch.
=======
This is the new code from your feature branch.
>>>>>>> feature-branch

Step 2: The Mediation Game

Now comes the fun part — resolving the conflict. Grab a virtual gavel and get ready to mediate between these code titans. Here’s how:

Review the Conflict:

Carefully examine the code that Git presents. The <<<<<<< HEAD marker signifies the code from the current branch (in this case, main), while the >>>>>>> feature-branch marker signifies the code from your feature branch. The ======= line acts as a divider. Your mission is to decide which code stays, which goes, and if necessary, craft a magical blend.

Step 3: Fun with Edits

Use your coding wand (keyboard) to make the necessary changes. You can keep one version, both, or even create an entirely new piece of code. The power is in your hands.

Step 4: Removing the Markers

When you’re satisfied with your resolution, cast a spell to eliminate the conflict markers (<<<<<<< HEAD, =======, >>>>>>> feature-branch) from your code. They're no longer needed.

Step 5: Saving the Day

Commit your changes with a thoughtful message that tells the tale of how you resolved this epic conflict.

Step 6: The Grand Finale

You’re almost there! All that’s left is to complete the merge, which can usually be done by running:

git merge main

Or if you were in the middle of a pull request, go back to the pull request on GitHub and click that glorious “Merge” button.

And voilà! The merge conflict has been resolved, and your code lives harmoniously ever after.

In the whimsical world of Git, merge conflicts can seem like code battles, but with a sprinkle of patience and a dash of whimsy, they become opportunities to make your code even better. So next time a merge conflict arises, don your coding armor and bravely charge in, ready to conquer and emerge victorious! Happy coding, oh valiant developer! 🚀

Resolving Merge Conflicts with Rebase: A Playful Guide for the Git Savvy

Ah, merge conflicts, those little hiccups in your Git journey. But fret not, brave coder! We’re about to embark on a whimsical adventure in conflict resolution, using Git’s rebase as our trusty steed.

Setting the Stage

Imagine you’re sailing on the good ship feature-branch towards the shores of main. But wait, there's a storm brewing! A merge conflict arises. The code you're about to merge seems to have a conflict with the current main.

Introducing the Rebase Magic Wand

In our magical world of Git, we have a special wand called “rebase.” It’s not just for wizards; you can wield it too! But remember, with great power comes great responsibility.

The Grand Rebase Adventure

Time to set sail and resolve the conflict:

Step 1: Pause and Create a Stash
First, let’s pause the merging and stash your changes for safekeeping. We don’t want to lose anything during the journey.

git stash save "My Fantastic Changes"

Step 2: Update Your feature-branch
Next, we'll update our branch with the latest code from main using rebase.

git checkout feature-branch
git pull --rebase origin main

Step 3: Conquer the Conflict
Now, it’s time to resolve the conflict. Open the conflicted file in your code editor and work your magic. Choose the bits you want to keep, delete the rest, and remove those pesky conflict markers.

Step 4: Finalise the Rebase
Once you’ve tamed the stormy seas of conflict, it’s time to continue the rebase.

git add .  # Stage your changes
git rebase --continue

Step 5: Restore Your Stash
With the rebase complete, let’s bring back your fantastic changes from the stash.

git stash pop

Celebrate and Merge

With the conflict resolved and your code harmonised, it’s time to celebrate! You’re ready to sail smoothly into the main branch.

  • If you were in the middle of a pull request on GitHub, go back to the pull request and merge it with ease.
  • If you were doing this all locally, merge your feature-branch into main:
git checkout main
git merge feature-branch

And there you have it, a whimsical tale of rebase wizardry to resolve those pesky merge conflicts. Git might throw you a curveball from time to time, but with a bit of Git magic, your code will be singing in perfect harmony once again. Happy coding, oh mighty wizard of Git! 🪄🧙‍♂️

Finally understand git rebase — (Generated using Supermeme.ai)

Why Git Rebase is Safer and Easier Than Git Merge: A Tale of Harmony and Flow

In the epic battle of Git commands, rebase and merge each wield their own set of powers. While both serve to combine changes from one branch into another, rebase emerges as the champion when it comes to safety and simplicity. Let's embark on a journey to explore why rebase reigns supreme.

The Mighty Merge

Imagine a world where branches are like rivers, and you need to combine their waters. That’s what merge does. It creates a new commit that has two parent commits, preserving the complete history of both branches. While noble in intent, this often results in a history that looks like a tangle of vines, making it a tad harder to follow.

The Regal Rebase

Now, consider a land where branches flow like parallel streams. Rebase takes the changes in your branch and applies them on top of another branch. It rewrites the commit history, making it seem like your changes were there from the beginning. The result is a clean and linear history, akin to reading a captivating story.

Resolving Conflicts with Ease

In the realm of conflicts, rebase has a clever approach. It applies your changes one by one, giving you the chance to resolve conflicts as they occur. This means you tackle conflicts in smaller, manageable chunks, making the process less overwhelming.

Merge, on the other hand, tends to lump all conflicts together, creating a more challenging puzzle to solve.

The Safety Net

Safety is of utmost importance in our Git saga. With rebase, you work on a copy of your branch, keeping your original branch pristine. In case of any missteps, your original branch remains untouched and safe.

With merge, you often end up with extra merge commits in your history, potentially causing confusion and clutter. The original branch gets mixed up in the merging process, which can sometimes lead to messy conflicts.

The Elegance of Simplified History

In the grand finale, rebase stands victorious as the command that simplifies your project's history. It encourages a linear, readable narrative that's easier to follow, with changes flowing seamlessly from one branch to another.

The Power of Choice

In the grand tapestry of Git, both rebase and merge serve their roles. But rebase excels in creating clean, harmonious histories, making it the go-to choice when you want to keep your project's story crystal clear. And in the end, isn't it the elegant simplicity and fluidity that make a story truly enchanting?

GitHub Pages and Actions — Empowering Your Web Presence with GitHub Magic

In the enchanting world of Git and GitHub, GitHub Pages and GitHub Actions shine as your mystical allies, conjuring up web hosting and automation like seasoned wizards. Let’s unravel their spellbinding powers in this chapter.

GitHub Pages — The Portal to Digital Realms

GitHub Pages is your gateway to hosting websites with all the charm of a fairy tale. Picture it as the magic wardrobe to Narnia, but for your web projects. With GitHub Pages, you can transform your repositories into live websites. It’s as simple as writing your code, pushing it to a special repository, and voila! Your website is live, accessible to the world. GitHub Pages transforms your code into captivating online experiences, whether it’s a personal blog, a portfolio, or a documentation hub.

GitHub Actions — The Automation Maestros

Now, imagine GitHub Actions as the orchestra conductor of your digital theater. These automation maestros ensure that your workflows are as smooth as a virtuoso’s performance. From building and testing to deploying your projects, GitHub Actions automates it all, making sure your code dances flawlessly on the digital stage.

The Symphony of Collaboration

But the real magic happens when GitHub Pages and GitHub Actions join forces. They harmonize like a well-tuned orchestra, orchestrating a seamless automation symphony. Push your code, and GitHub Actions takes the lead, making sure your website is always up-to-date, as if it were rehearsing for a grand performance. This dynamic duo keeps your web projects in sync with your repository changes, ensuring your online presence is as polished as a Broadway show.

The Standing Ovation

And there you have it, a mesmerizing combination of GitHub Pages and Actions, where hosting websites becomes a breeze and automating workflows is a masterstroke. Your web projects get the applause they deserve, while you bask in the glory of a well-executed performance.

With GitHub Pages and GitHub Actions, you hold the wand to create enchanting online experiences and automate tasks with ease. It’s like having a digital magic show at your fingertips, where your projects take center stage and shine brightly in the online spotlight. Happy coding, and may your web presence be as magical as a spell! 🪄🌐🎩

Navigating the Git Galaxy with Confidence

In the grand orchestra of Git and GitHub, conducting a masterpiece is an art. To ensure your coding endeavors are like a harmonious symphony, we’ll dive into the best practices that make your collaboration efficient and your code as polished as a virtuoso’s performance.

Coding Standards — The Notes to Harmony

Just as a musical composition follows notes, your code should adhere to coding standards. It’s like following the sheet music in a concerto. Choose a coding style guide (like PEP8 for Python, ESLint for JavaScript, or others for different languages) and stick to it. Consistency is the key to readability and maintainability. It ensures that your code is like a beautifully composed score, where every contributor knows their part, creating a harmonious codebase.

Commit Message Conventions — The Lyrics of Your Code

And there you have it, dear fellow developers, the journey through the Git galaxy is complete. From seasoned coding veterans to those just starting their voyage into the world of software development, you’ve traversed the terrain of Git commands, learning not just the basics but also harnessing the power of best practices.

Our expedition through this command-line universe has equipped you with the knowledge and tools to enhance your coding prowess. You’ve unlocked the secrets of streamlined workflows, seamless collaboration, and confident code maintenance.

As you disembark from this enlightening adventure, remember that Git is your trusty companion in crafting exceptional code. The journey doesn’t end here; it’s a continuum. Your newfound Git skills will empower you to contribute effectively to any development project, no matter how complex or extensive.

If you ever wish to reach out with questions, collaborations, or simply to connect, you can find me on,

drop me an email at thinuralaksara@gmail.com 📧. And if you’d like to buy me a coffee as a token of appreciation for this guide, you can do so through this link Buy Coffee ☕.

So, as you venture forth into your coding endeavours, may Git be your North Star, guiding you through the vast sea of code, helping you create, collaborate, and innovate. Here’s to the next chapter of your coding adventure. Happy coding! 🚀🌌👩‍💻

--

--