Working with Branches in Git

Tutorial 1 of 5

1. Introduction

This tutorial is designed to guide you through the process of creating, switching, and deleting branches in Git, a crucial skill for any software developer. By the end of this tutorial, you will be able to manage your Git branches effectively to streamline your workflow and collaborate more efficiently.

Prerequisites: Basic understanding of Git and version control.

2. Step-by-Step Guide

A branch in Git is essentially a unique set of code changes with a unique name. The default branch name in Git is "master". When you make changes, you're actually making changes to your own branch, not the master branch.

To create a new branch:

git branch <branch-name>

To switch to a different branch:

git checkout <branch-name>

To delete a branch:

git branch -d <branch-name>

Note: You can't delete a branch if you're currently on it. You must switch to another branch before deleting.

3. Code Examples

Creating a new branch and switching to it:

# Create a new branch named 'new-feature'
git branch new-feature

# Switch to the 'new-feature' branch
git checkout new-feature

Deleting a branch:

# Switch back to the master branch
git checkout master

# Delete the 'new-feature' branch
git branch -d new-feature

4. Summary

In this tutorial, we've learned how to create, switch, and delete branches in Git. This is a fundamental skill for any developer and is essential for efficient collaboration and version control.

For further learning, explore merging branches and resolving conflicts in Git. The official Git documentation is a valuable resource for this.

5. Practice Exercises

  1. Create a new branch named 'test-branch', switch to it, create a new file, add some content, and commit it.

  2. Solution:
    ```bash
    # Create and switch to a new branch named 'test-branch'
    git checkout -b test-branch

    # Create a new file
    echo "This is a test file." > test.txt

    # Add the new file to the staging area
    git add test.txt

    # Commit your changes
    git commit -m "Add test file"
    ```

  3. Switch back to the master branch and try to delete the 'test-branch'. What happens and why?

  4. Solution: You can't delete a branch that has unmerged changes. Git prevents you from losing those changes.

  5. Merge 'test-branch' into the master branch and then delete 'test-branch'.

  6. Solution:
    ```bash
    # Switch to the master branch
    git checkout master

    # Merge 'test-branch' into the master branch
    git merge test-branch

    # Delete 'test-branch'
    git branch -d test-branch
    ```

Remember to keep practicing these commands until you're comfortable with them. They are core to your workflow in Git.