In a Git repository, a branch is like a separate line of development. Each branch represents a different version of the project. The master branch is the main branch, and usually, new features and bug fixes are developed on separate branches before being merged into the master.
$ git branch
* master
feature-A
bugfix-B
In this example, we have three branches: master, feature-A, and bugfix-B. The * indicates that the current branch is master.
To create a new branch, use the git branch command followed by the name of the new branch.
$ git branch new-branch
To switch to the newly created branch, use the git checkout command followed by the name of the branch.
$ git checkout new-branch
Now that we're on the new-branch, we can make changes, add files, and commit them.
$ touch new-file.txt
$ git add new-file.txt
$ git commit -m "Adding new file on new-branch"
Once we're done with a branch and want to delete it, we can use the git branch -d command followed by the name of the branch.
$ git branch -d new-branch
š Note: You cannot delete the current branch. If you try to delete the current branch, Git will prevent you from doing so. You'll have to switch to another branch and then delete the current one.
If you've pushed your branch to a remote repository (for example, GitHub), you'll need to delete the remote branch as well. To do that, first, fetch the remote branch using git fetch origin. Then, delete the local branch as shown earlier. Finally, delete the remote branch using git push origin --delete <branch-name>.
$ git fetch origin
$ git branch -d new-branch
$ git push origin --delete new-branch
Some hosting services like GitHub offer branch protection to prevent accidental deletion of important branches. In such cases, you'll need to disable branch protection before deleting the branch.
What does the `git branch -d` command do?
In a real-world scenario, you might create a new branch for a feature or a bug fix. After you're done with the changes, you'll merge the branch into the master branch and then delete the feature branch.
$ git checkout master
$ git merge feature-A
$ git checkout feature-A
$ git branch -d feature-A
$ git push origin --delete feature-A
In this example, we first switch to the master branch, merge the changes from the feature-A branch, switch back to the feature-A branch, delete it, and finally delete the remote branch.
By following this workflow, you can manage your Git branches effectively and keep your projects organized. š