Git Branching Commands

 

1. Creating a Branch

To create a new branch, you use the git branch command followed by the name of the new branch.

For example:

git branch feature-branch

This command creates a new branch named feature-branch but doesn't switch to it yet.

2. Switching Branches

To switch to a different branch, you use the git checkout command followed by the name of the branch.

For example:

git checkout feature-branch

This command switches to the feature-branch so that any changes made will be applied to that branch.

3. Creating and Switching to a New Branch Simultaneously

You can create and switch to a new branch in a single command using git checkout -b.

For example:

git checkout -b new-feature

This command creates a new branch named new-feature and switches to it.

4. Listing Branches

You can list all branches in your repository using the git branch command.

For example:

git branch

This command will list all branches, with an asterisk (*) indicating the current branch.

5. Merging Branches

Once you've made changes in a branch and want to incorporate those changes into another branch (usually the main branch), you perform a merge. For example, if you're on the feature-branch and want to merge it into main:

git checkout main

git merge feature-branch

This will merge the changes from feature-branch into main.

6. Deleting Branches

After merging a branch into another branch, you might want to delete the now-merged branch. You can do this using the -d flag with git branch.

For example:

git branch -d feature-branch

This will delete the feature-branch.

Example Scenario:

Let's say you're working on a new feature for a project. You create a new branch called new-feature:

git checkout -b new-feature

You make changes to the code, commit them:

git add .

git commit -m "Implemented new feature"

Then, you switch back to the main branch and merge your changes:

git checkout main

git merge new-feature

Finally, you delete the new-feature branch since it's no longer needed:

git branch -d new-feature


This workflow allows you to keep your main branch clean and stable while working on new features or bug fixes in separate branches.




Followers