Deleting a Branch
After you have finished working on a branch and its changes have been merged into another branch (like master
), you can delete the branch to keep your repository clean.
Navigate to the Git repository directory if you are not already there:
cd /home/labex/project/my-git-repo
Before deleting the feature/add-new-file
branch, you need to switch back to another branch, for example, the master
branch. You cannot delete the branch you are currently on.
Switch back to the master
branch:
git checkout master
Output:
Switched to branch 'master'
Your branch is up to date with 'origin/master'.
Now, you can delete the feature/add-new-file
branch using the git branch -d
command. The -d
flag is a safe way to delete a branch because Git prevents you from deleting the branch if it contains unmerged changes.
Execute the following command to delete the branch:
git branch -d feature/add-new-file
Output:
Deleted branch feature/add-new-file (was abcdefg).
(Note: The commit hash abcdefg
will be different in your output.)
You can verify that the branch is deleted by listing the branches again:
git branch
Output:
* master
The feature/add-new-file
branch is now gone.
If you ever need to delete a branch that has unmerged changes (use with caution!), you can use the -D
flag instead of -d
.
You have successfully learned how to check the current branch, create a new branch, switch between branches, and delete a branch.