Git Branch

The git branch command is a fundamental tool for creating, listing, and manipulating branches. We'll delve into various ways to use the git branch command, demonstrating its versatility and importance in the development workflow.

1. Creating a New Branch:

The primary purpose of the git branch command is to create a new branch. To do this, simply provide the branch name:

bash
git branch new-feature

This creates a new branch named "new-feature" without switching to it.

2. Listing Branches:

To see a list of existing branches in your repository, use the following command:

bash
git branch

The current branch is indicated with an asterisk (*). Optionally, use -a to display remote branches as well.

3. Switching Between Branches:

Use the git checkout command or its successor, git switch, to switch between branches:

bash
git switch new-feature

This command updates the working directory to the specified branch.

4. Creating and Switching to a New Branch:

Combine branch creation and switching into a single command:

bash
git switch -c feature-branch

This is a shorthand way to create and switch to a new branch simultaneously.

5. Renaming a Branch:

To rename a branch, use the -m option with git branch:

bash
git branch -m old-branch new-branch

This is useful for maintaining a consistent and meaningful branch naming convention.

6. Deleting a Branch:

Remove a branch using the -d or -D option:

bash
git branch -d obsolete-branch

The -d option deletes the branch only if its changes are already merged into the current branch, while -D forces deletion.

7. Viewing the Last Commit on Each Branch:

To see the last commit on each branch, use the git show-branch command:

bash
git show-branch

This provides a quick overview of the commit history on all branches.

8. Tracking Remote Branches:

To create a new local branch that tracks a remote branch, use the following command:

bash
git branch -t local-branch origin/remote-branch

This establishes a connection between the local and remote branches.

9. Setting Upstream Branch:

Establish a tracking relationship between a local and remote branch using the -u option:

bash
git branch --set-upstream-to=origin/main main

This ensures that future git pull and git push commands work without specifying the remote and branch names.