Git Branch Basic Operations

GitGitBeginner
Practice Now

Introduction

This lab is designed to teach you how to use git commands such as branch, checkout, merge, and log. There are four steps, each of which corresponds to a specific command.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/BranchManagementGroup(["`Branch Management`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) git/BranchManagementGroup -.-> git/branch("`Handle Branches`") git/BranchManagementGroup -.-> git/checkout("`Switch Branches`") git/BranchManagementGroup -.-> git/merge("`Merge Histories`") git/BranchManagementGroup -.-> git/log("`Show Commits`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") subgraph Lab Skills git/branch -.-> lab-8435{{"`Git Branch Basic Operations`"}} git/checkout -.-> lab-8435{{"`Git Branch Basic Operations`"}} git/merge -.-> lab-8435{{"`Git Branch Basic Operations`"}} git/log -.-> lab-8435{{"`Git Branch Basic Operations`"}} linux/cd -.-> lab-8435{{"`Git Branch Basic Operations`"}} end

Creating Branches

In Git, a branch is a separate line of development that allows you to work on a feature or bug fix without affecting the main codebase. To create a new branch, use the branch command followed by the name of the new branch:

cd ~/project/myrepo
git branch new-feature

This command creates a new branch named new-feature that is identical to the current branch. You can now switch to this new branch using the checkout command:

git checkout new-feature

Renaming and Deleting Branches

If you want to rename a branch, use the branch command with the -m option followed by the new name:

git branch -m old-name new-name

To delete a branch, use the branch command with the -d option followed by the name of the branch you want to delete:

git branch -d branch-to-delete

Merging Branches

Once you have made changes to a branch, you can merge it back into the master codebase using the merge command. First, switch back to the master branch:

git checkout master

Then, use the merge command followed by the name of the branch you want to merge:

git merge new-name

This command will merge the changes from new-name into the master branch.

Viewing Branch History

The log command allows you to view the commit history of a branch:

git log

This command shows you the commit history for the current branch, including the commit message, author, and timestamp.

You have to press q to exit to view the logs.

Summary

In this lab, you learned how to create, rename, delete, merge, and view the commit history of branches using Git commands. By using these commands, you can work on features and bug fixes in separate branches, collaborate with other developers, and maintain a clean and organized codebase.

Other Git Tutorials you may like