Git Branch Basic Operations

GitGitBeginner
Practice Now

Introduction

Welcome back, time traveler! Now, we're going to take your time-traveling skills to the next level with Git branches!

Imagine if you could create alternate universes for your project, where you can experiment with wild ideas without messing up your main timeline. That's exactly what Git branches let you do! They're like parallel dimensions for your code, where you can develop new features, fix bugs, or try out crazy experiments without fear.

By the end of this lab, you'll be a master of the multiverse, able to create new realities (branches), jump between them (checkout or switch), combine them (merge), and even delete universes you no longer need. These superpowers are essential for any time-traveling developer, whether you're working solo or as part of a team of dimension-hopping coders.

Are you ready to become a Git branch wizard? Let's dive in!


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/SetupandConfigGroup(["`Setup and Config`"]) git(("`Git`")) -.-> git/BasicOperationsGroup(["`Basic Operations`"]) git(("`Git`")) -.-> git/BranchManagementGroup(["`Branch Management`"]) git/SetupandConfigGroup -.-> git/init("`Initialize Repo`") git/BasicOperationsGroup -.-> git/add("`Stage Files`") git/BasicOperationsGroup -.-> git/commit("`Create Commit`") git/BranchManagementGroup -.-> git/branch("`Handle Branches`") git/BranchManagementGroup -.-> git/checkout("`Switch Branches`") git/BranchManagementGroup -.-> git/merge("`Merge Histories`") git/BranchManagementGroup -.-> git/log("`Show Commits`") subgraph Lab Skills git/init -.-> lab-385163{{"`Git Branch Basic Operations`"}} git/add -.-> lab-385163{{"`Git Branch Basic Operations`"}} git/commit -.-> lab-385163{{"`Git Branch Basic Operations`"}} git/branch -.-> lab-385163{{"`Git Branch Basic Operations`"}} git/checkout -.-> lab-385163{{"`Git Branch Basic Operations`"}} git/merge -.-> lab-385163{{"`Git Branch Basic Operations`"}} git/log -.-> lab-385163{{"`Git Branch Basic Operations`"}} end

Setting Up Your Multiversal Hub

First, we need to create a central hub for all our alternate realities. This will be our main Git repository.

  1. Open your terminal. This is your control panel for jumping between dimensions.

  2. Navigate to your project space:

cd ~/project

This command changes your current directory to the "project" folder in your home directory. If you're ever unsure about where you are, you can use the pwd command to print your current working directory. This is a useful trick to remember if you ever get lost in the terminal.

  1. Let's create a new folder for our multiversal experiments:
mkdir git-branch-lab
cd git-branch-lab

The mkdir command creates a new directory, and then we use cd to move into it. This gives us a clean slate to work with. Think of this new folder as the control room of our time-traveling operation.

  1. Now, let's initialize our hub (Git repository):
git init

This command creates a new Git repository in the current directory. It sets up all the necessary files that Git needs to start tracking your project. These files are hidden in a folder called .git.

You should see a message like:

Initialized empty Git repository in /home/labex/project/git-branch-lab/.git/

Congratulations! You've just created a hub for infinite possibilities! This is the foundation upon which all your time-traveling adventures will be built.

  1. Let's create a note to our future selves explaining what this place is:
echo "## Git Branch Lab" > README.md
echo "This is my hub for multiversal Git branch experiments" >> README.md

Here's what these commands do:

  • The first command creates a new file called README.md and writes "## Git Branch Lab" into it. In Markdown, the '#' symbol creates a heading. This file will act as the user manual for our multiverse hub.
  • The second command appends another line to README.md. The '>>' means "add this to the end of the file". We're adding some detail to our user manual.

If you're curious about what you've just created, you can use the cat README.md command to view the contents of the file. This command is like reading the user manual for our multiverse hub.

  1. Now, let's make our first save point (commit) in this new universe:
git add README.md
git commit -m "Initial commit: Create the multiverse hub"

Let's break this down:

  • git add README.md tells Git to start tracking changes to README.md. This stages the file for commit. Think of staging as preparing the file for travel.
  • git commit creates a new commit (save point) with the staged changes. This is like taking a snapshot of our current universe.
  • The -m flag allows you to provide a commit message directly. Always try to write clear, descriptive commit messages! This message is like a note explaining what we changed in this snapshot.

If you're ever unsure about what's been staged or committed, you can use git status to check. This is like checking the status of our time-traveling equipment.

Creating Your First Alternate Reality

Now that we have our main universe (master branch) set up, let's create our first alternate reality!

  1. Create a new branch named feature-dimension:
git branch feature-dimension

This command creates a new branch, but doesn't switch to it yet. Think of it as creating a new parallel universe, but you're still in the original one. It's like having a blueprint for a new reality, but you haven't stepped into it yet.

You've just created a new timeline, but you're not in it yet. Let's see all the timelines we have:

git branch

You should see:

  feature-dimension
* master

The * shows which reality you're currently in. Right now, you're still in the main universe (master). The master branch is the default branch that Git creates when you initialize a new repository.

Tips: Press q to exit the branch list and return to your terminal.

  1. Let's jump into our new reality:
git checkout feature-dimension

This command does two things:

  1. It switches your current working directory to the feature-dimension branch.
  2. It updates the files in your working directory to match the state of the feature-dimension branch. It's like stepping through a portal into the new reality.

Now if you run git branch again, you'll see:

* feature-dimension
  master

The * has moved, showing that you've successfully jumped to your new dimension! You're now working in this alternate reality.

Alternatively, you can use git switch feature-dimension to achieve the same result. git switch is a newer command introduced in Git 2.23 that is specifically designed for branch switching, making it clearer and more intuitive. Both commands achieve the same result, but git switch is generally preferred for its clarity.

Don't worry if you don't see any changes in your files yet. When you create a new branch, it starts as an exact copy of the branch you were on. The exciting part comes when we start making changes! These initial copies ensure that each reality starts with the same foundation.

Pro tip: In newer versions of Git, you can create a new branch and jump to it in one command: git checkout -b feature-dimension or git switch -c feature-dimension. It's like creating and stepping into a portal in one swift move! Using -b with git checkout or -c with git switch combines branch creation and switching into a single step.

If you ever get lost and can't remember which dimension (branch) you're in, just run git branch again. The branch with the * is your current location. It's like checking your location on a map of the multiverse.

Shaping Your New Reality

Now that we're in our new dimension, let's make some changes that only exist here. Remember, whatever we do here won't affect our main universe until we decide to merge them. This allows us to safely experiment without disrupting our main timeline.

  1. Let's create a new artifact in this reality:
echo "This is a powerful artifact from another dimension" > dimensional-artifact.txt

This command creates a new file called dimensional-artifact.txt and writes a message into it. The > symbol is used to create a new file (or overwrite an existing one) with the given content. This artifact is unique to our current reality.

  1. Now, let's preserve this artifact in our timeline:
git add dimensional-artifact.txt
git commit -m "Create a powerful interdimensional artifact"

These commands should be familiar from Step 1. We're telling Git to track our new file and then creating a save point with a descriptive message. These commands are like taking a snapshot of the newly discovered artifact.

  1. Let's also update our note to future selves about this new reality:
echo "##### Feature Dimension" >> README.md
echo "We've discovered a powerful artifact in this reality" >> README.md

These commands are adding new lines to our README.md file. The >> symbol appends to an existing file instead of overwriting it. We're updating our user manual to reflect our discoveries in the new dimension.

  1. Let's save these changes too:
git add README.md
git commit -m "Document the discovery of the artifact"

Again, we're creating another save point, this time for our updated README.md file. We're preserving the updated documentation for our future selves.

Great job! You've now made changes in your alternate reality. These changes exist only in the feature-dimension branch for now. If you were to switch back to the master branch, you wouldn't see these changes there. This separation ensures that our experimentation in one reality doesn't impact the others.

To see the difference between your current branch and the master branch, you can use the command git diff master. This will show you all the changes you've made in your current reality compared to the main timeline. This is like comparing the state of the two universes.

Merging Realities

Now that we've made amazing discoveries in our alternate reality, it's time to bring them back to our main universe. This process is called merging.

  1. First, let's jump back to our main reality:
git checkout master

or

git switch master

Both commands switch us back to the master branch.

  • git checkout is the older command for switching branches. It's been around since the early days of Git and is still supported.
  • git switch is the newer command introduced in Git 2.23. It's designed to be more intuitive and easier to understand.

You can use either command to switch branches, but git switch is generally preferred for its clarity.

If you look at your files now, you'll notice that your interdimensional artifact is gone! Don't worry, it's safe in the other dimension. This demonstrates that changes in one branch are isolated from other branches until they are merged.

  1. Now, let's merge our alternate reality into the main timeline:
git merge feature-dimension

This command tells Git to take all the changes from feature-dimension and apply them to master. It's like integrating the discoveries from our alternate reality into our main universe.

You should see a message like:

Updating <hash1>..<hash2>
Fast-forward
 README.md              | 2 ++
 dimensional-artifact.txt | 1 +
 2 files changed, 3 insertions(+)
 create mode 100644 dimensional-artifact.txt

This output tells you what files were changed and how many lines were added or removed. "Fast-forward" means Git was able to simply move the master branch forward to where feature-dimension was, because there were no conflicting changes. A fast-forward merge is the simplest type of merge, and occurs when the branch you are merging into hasn't changed since the branch you are merging from was created.

Congratulations! You've just combined two realities! The changes we made in feature-dimension are now part of our main universe. Our interdimensional artifact and the updated documentation are now present in our master branch.

  1. Let's confirm that our artifact made it through the merge:
cat dimensional-artifact.txt
cat README.md

These commands will display the contents of the files. You should see the changes we made in the feature-dimension. These commands verify that the merge was successful.

You've successfully brought your discoveries from an alternate reality into the main timeline. This is how developers bring new features into their main project! This is a core concept in Git that allows developers to work on features in isolation, and then integrate them into the main codebase when they are ready.

If you want to see a list of all the branches that have been merged into your current branch, you can use the command git branch --merged. This can be useful to track which branches have been integrated.

Closing Dimensional Portals

Now that we've successfully brought our discoveries back to the main reality, we can close the portal to our alternate dimension. In Git terms, we'll delete the branch we no longer need.

  1. Let's close our feature-dimension portal:
git branch -d feature-dimension

The -d flag tells Git to delete the branch, but only if it's been fully merged. It's a safety measure to prevent accidental loss of unmerged changes. Git will only allow you to delete a branch using -d if the changes in it have been merged to the branch you are on.

If you try to delete a branch that hasn't been fully merged, Git will give you a warning. In such cases, if you're absolutely sure you want to delete the branch, you can use the -D flag instead: git branch -D feature-dimension. This force-deletes the branch regardless of its merge status. Be careful with this power! This command should only be used when you are absolutely sure you don't need the changes in the branch.

  1. Let's check which realities still exist:
git branch

You should only see the master branch now. This indicates that the portal to the feature-dimension is now closed.

Cleaning up old branches keeps your multiverse organized. It's a good habit to close portals to dimensions you no longer need, especially when working on larger projects with many alternate realities. This keeps your workspace clean and prevents confusion.

If you ever want to see all branches, including remote branches, you can use git branch -a. This can be helpful when working on projects with multiple contributors. Remote branches are copies of branches on other repositories.

Summary

Congratulations, master of the multiverse! You've just completed your crash course in Git branch wizardry. Let's recap the incredible feats you've accomplished:

  1. You created a hub for infinite possibilities (a new Git repository).
  2. You opened a portal to an alternate reality (created a new branch).
  3. You learned to jump between different dimensions (switch branches using git checkout or git switch).
  4. You made groundbreaking discoveries in a parallel universe (committed changes in a separate branch).
  5. You merged two realities, bringing your discoveries into the main timeline (merged branches).
  6. Finally, you learned how to close dimensional portals you no longer need (delete branches).

These multiversal skills are crucial for any time-traveling developer. By using branches, you can:

  • Work on different features or bug fixes in parallel universes, without disrupting the main timeline.
  • Experiment with wild ideas in safe, alternate realities.
  • Collaborate with other dimension-hopping developers, each working in their own reality.
  • Keep your main timeline stable and glitch-free, only merging in new features when they're ready.

Happy dimension hopping, and may your merges always be conflict-free!

Other Git Tutorials you may like