Branches in Git

Photo by Yancy Min on Unsplash

Branches in Git

Branch is a lightweight, movable pointer to a commit. The default branch name in Git is typically "master," but you can create and switch to other branches to isolate work and manage changes more efficiently. Branches are an essential part of Git's flexibility and support for parallel development. They allow multiple developers to work on different features or bug fixes simultaneously without interfering with each other. Branches also enable you to experiment with new ideas without affecting the main codebase until you are ready to merge changes.

Key concepts related to branches in Git:

  1. Default Branch:

    • When you initialize a new Git repository or clone an existing one, Git creates a default branch called "master." However, note that some repositories now use "main" as the default branch name.
  2. Creating a Branch:

    • You can create a new branch using the git branch command. For example:

        git branch new-feature
      
  3. Switching Between Branches:

    • The git checkout or git switch commands allow you to switch between branches. For example:

        git checkout new-feature
      

      or

        git switch new-feature
      
  4. Creating and Switching in One Step:

    • You can create a new branch and switch to it in a single command using the -b option with git checkout or git switch:

        git checkout -b new-feature
      

      or

        git switch -c new-feature
      
  5. Viewing Branches:

    • To see a list of branches in your repository and identify the currently active branch, use:

        git branch
      
  6. Merging Branches:

    • After making changes in a branch, you can merge those changes back into another branch using the git merge command. For example:

        git checkout main
        git merge new-feature
      
  7. Deleting a Branch:

    • Once a branch is no longer needed, you can delete it using the git branch -d command. For example:

        git branch -d new-feature
      
  8. Deleting Remote Branch:

    • To delete a branch on remote use git push <remote name> :<branch name> command. For example:

        git push origin :new-feature
      
  9. Renaming a Branch:

    • You can rename a branch using the git branch -m command. For example, to rename "feature-abc" to "new-feature":

        git branch -m feature-abc new-feature