This article will demonstrate:
How to Close a Particular Git Branch?
To close a branch in Git, look at the following steps:
- Switch to the local directory.
- View all available branches.
- Select the desired branch that needs to be closed.
- Tag the selected branch by archiving it using the “git tag archive/<branch-name> <branch-name>” command.
- Delete/remove the branch from the repository by utilizing the “git branch -D <branch-name>” command.
- Verify changes.
Step 1: Redirect to Local Repository
First, navigate to the desired local repository:
Step 2: View Branches
Then, list all the available repository branches:
The below image displays all the current repository’s branches. Now, choose the desired branch that needs to be closed. For instance, we have selected the “feature” branch:
Step 3: Tag Branch
To store the backup of the branch that needs to be closed, tag the selected branch by archiving it using the below-listed command:
The above-provided command has created the backup for the “feature” branch:
Step 4: Delete Branch
Now, utilize the following command along with the selected branch name to delete it from the current repository:
Step 5: Verify Deleted Branch
To ensure that the desired branch has been closed or deleted from the repository or not, run the following command:
It can be observed that the “feature” branch has been closed/deleted successfully:
How to Restore a Closed Branch in Git?
Sometimes, users want to restore the closed branch. Git allows them to retrieve any closed branch with its content using the “git checkout -b <branch-name> archive/<branch-name>” command. To do so, follow the provided steps.
Step 1: Restore Branch
To restore or retrieve the closed Git branch, check out the tag and recreate the deleted branch using the given-below command:
According to the below image, the “feature” branch has been restored, and we have switched to it:
Step 2: Verify Changes
Write out the following command to ensure that the desired branch has been restored:
In the below output, the “feature” branch can be seen, which is also the current branch:
Step 3: View Git Log
Lastly, view the restored branch history by checking the Git log:
As you can see, the branch has been restored successfully with its content and history:
That was all about closing and restoring a particular branch in Git.
Conclusion
To close a branch in Git, first, switch to the local directory and view all available branches. Then, choose the desired branch that needs to be closed. After that, tag that particular branch by archiving it using the “git tag archive/<branch-name> <branch-name>” command. Next, utilize the “git branch -D <branch-name>” command to delete the desired branch from the repository and verify changes. Moreover, users can retrieve the closed branch with the help of the “git checkout -b <branch-name> archive/<branch-name>” command. This article demonstrated the method to close and restore a specific branch in Git.