Git ~ Branch - rohit120582sharma/Documentation GitHub Wiki

A branch represents an independent line of development. Branches serve as an abstraction for the edit/stage/commit process.

You can think of them as a way to request a brand new working directory, staging area, and project history. New commits are recorded in the history for the current branch, which results in a fork in the history of the project.

If you change something on a branch, it doesn’t affect the master branch until you want it to. This means that you can do whatever you want to do on that branch until you decide it’s time to merge it.

The git branch command lets you create, list, rename, and delete branches. It doesn’t let you switch between branches or put a forked history back together again. For this reason, git branch is tightly integrated with the git checkout and git merge commands.



Creating Branches

It's important to understand that branches are just pointers to commits. When you create a branch, all Git needs to do is create a new pointer, it doesn’t change the repository in any other way.

List all of the branches in your repository. This is synonymous with git branch --list.

# List all local branches
$ git branch
# List all remote branches
$ git branch -a

Create a new branch called <branch>. This does not check out the new branch.

$ git branch <branch>

To start adding commits to it, you need to select it with git checkout, and then use the standard git add and git commit commands.



Creating remote branches

The git branch command also works on remote branches. In order to operate on remote branches, a remote repo must first be configured and added to the local repo config.

# pushes the <branch> branch to remote-repo
$ git push origin <branch>


Deleting Branches

Once you’ve finished working on a branch and have merged it into the main code base, you’re free to delete the branch without losing any history:

As you realize, there are 3 different branches that need to be deleted in Git:

  • The local <branch>
  • The remote origin/<branch>
  • The local remote-tracking branch origin/<branch> that tracks the remote <branch>
# Delete a remote branch
$ git push origin --delete <branch>

# Delete a local branch
$ git branch --delete <branch>
$ git branch -d <branch> # Shorter version
$ git branch -D <branch> # Force delete un-merged branches

# Delete a local remote-tracking branch
$ git branch --delete --remotes <remote>/<branch>
$ git branch -dr <remote>/<branch> # Shorter
$ git fetch <remote> --prune # Delete multiple obsolete tracking branches
$ git fetch <remote> -p # Shorter

⚠️ **GitHub.com Fallback** ⚠️