I have a branch called Test_Branch
. When I try to delete it using the recommend method, I get the following error:
Cannot delete branch ‘Test_Branch’ checked out at ‘[directory
location]’.
I get no other information besides that. I can blow away the remote branch easy but the local branch won’t go away.
j08691
201k31 gold badges257 silver badges270 bronze badges
asked Jan 5, 2017 at 18:35
Bob WakefieldBob Wakefield
3,5794 gold badges20 silver badges28 bronze badges
7
Switch to some other branch and delete Test_Branch
, as follows:
$ git checkout master
$ git branch -d Test_Branch
If above command gives you error — The branch 'Test_Branch' is not fully merged. If you are sure you want to delete it
and still you want to delete it, then you can force delete it using -D
instead of -d
, as:
$ git branch -D Test_Branch
To delete Test_Branch
from remote as well, execute:
git push origin --delete Test_Branch
answered Jan 5, 2017 at 18:37
Arpit AggarwalArpit Aggarwal
26.6k15 gold badges86 silver badges106 bronze badges
6
Ran into this today and switching to another branch didn’t help. It turned out that somehow my worktree information had gotten corrupted and there was a worktree with the same folder path as my working directory with a HEAD
pointing at the branch (git worktree list
). I deleted the .git/worktree/
folder that was referencing it and git branch -d
worked.
answered Sep 13, 2017 at 23:56
0
You probably have Test_Branch checked out, and you may not delete it while it is your current branch. Check out a different branch, and then try deleting Test_Branch.
answered Jan 5, 2017 at 18:38
0
If you have created multiple worktrees with git worktree, you’ll need to run git prune
before you can delete the branch
answered Dec 5, 2017 at 14:26
dkniffindkniffin
1,21617 silver badges24 bronze badges
3
In my case there were uncommitted changes from the previous branch lingering around. I used following commands and then delete worked.
git checkout *
git checkout master
git branch -D <branch name>
ggorlen
40k7 gold badges66 silver badges89 bronze badges
answered Sep 6, 2019 at 12:23
Most junior programmers that faced
Cannot delete branch 'my-branch-name'
Because they are already on that branch.
It’s not logical to delete the branch that you are already working on it.
Just switch to another branch like master
or dev
and after that delete the branch that you want:
git checkout dev
git branch -d my-branch-name
without force delete
, you can delete that branch
answered May 18, 2021 at 10:05
RaskulRaskul
1,3006 silver badges20 bronze badges
2
If you run into this problem where you have checkedout and not able to delete the branch and getting this error message
«error: Cannot delete branch ‘issue-123’ checked out at …..»
Then check the branch you are currently in by using
git branch
If the branch you are trying to delete is your current branch, you cannot delete the same. Just switch to the main or master or any other branch and then try deleting
git checkout main or master
git branch -d branchname
git branch -D branchname
git branch -D branchname —force
answered Sep 12, 2021 at 11:52
I had a similar problem except that the bad branch was in the middle of rebase.
git checkout bad_branch && git rebase --abort
solved my issue.
answered Sep 6, 2022 at 3:04
This worked for me…
I have removed the folders there in .git/worktrees folder and then tried «git delete -D branch-name».
answered Oct 2, 2018 at 19:08
VasuVasu
1292 silver badges9 bronze badges
Ran into this problem today for branches reported by git branch -a
and look like this one: remotes/coolsnake/dev
, i.e. a local references to «remote» branches in registered git remote add ...
remotes.
When you try
git branch -d remotes/coolsnake/dev
you’ll get the error: branch 'remotes/coolsnake/dev' not found
.
The magic is to remember here that these are references and MUST be deleted via
git update-ref -d remotes/coolsnake/dev
(as per https://superuser.com/questions/283309/how-to-delete-the-git-reference-refs-original-refs-heads-master/351085#351085)
Took a while to uncover my mistake and only the fact that TortoiseGit could do it led me on the right path when I was stuck. Google DID NOT deliver anything useful despite several different approaches. (No that I’ve found what I needed there’s also git: How to delete a local ref branch?, which did NOT show up as I had forgotten the ‘ref’ bit about these branches being references.)
Hope this helps someone else to get unstuck when they’re in the same boat as me, trying to filter/selectively remove branches in a repo where some of them are present due to previous git remote add
commands.
In a shell script this then might look like this:
#! /bin/bash
#
# Remove GNU/cesanta branches so we cannot accidentally merge or cherrypick from them!
#
# commit hash is first GNU commit
R=218428662e6f8d30a83cf8a89f531553f1156d25
for f in $( git tag -l ; git branch -a ) ; do
echo "$f"
X=$(git merge-base $R "$f" )
#echo "X=[$X]"
if test "$X" = "$R" ; then
echo GNU
git branch -D "$f"
git update-ref -d "refs/$f"
git tag -d "$f"
#git push origin --delete "$f"
else
echo CIVETWEB
fi
done
answered Apr 3, 2021 at 17:47
Ger HobbeltGer Hobbelt
1,0861 gold badge9 silver badges15 bronze badges
Like others mentioned you cannot delete current branch in which you are working.
In my case, I have selected «Test_Branch» in Visual Studio and was trying to delete «Test_Branch» from Sourcetree (Git GUI). And was getting below error message.
Cannot delete branch ‘Test_Branch’ checked out at ‘[directory
location]’.
Switched to different branch in Visual Studio and was able to delete «Test_Branch» from Sourcetree.
I hope this helps someone who is using Visual Studio & Sourcetree.
answered Jul 11, 2019 at 17:27
Praveen MittaPraveen Mitta
1,3782 gold badges25 silver badges48 bronze badges
If any of the other answers did not work for you,
this can also happen if you are in the middle of a rebase.
So either finish the rebase or abort it:
git rebase --abort
Afterward, you can remove the branch.
answered Jan 25 at 7:58
Guy sGuy s
1,4663 gold badges17 silver badges27 bronze badges
ran into same problem,
checked out to different branch and used git branch -D branch_name
worked for me
answered Aug 1, 2022 at 10:20
git branch --D branch-name
Please run this code to delete
answered Oct 31, 2022 at 6:15
Whether you use GitFlow, GitHub Flow or any other branch driven development strategy, you will inevitably end up with a local Git repository filled with branches you no longer need. Which is why it’s good to know the command to delete Git branches locally and permanently so they don’t pollute your local development environment.
How to delete local Git branches
To issue the command to delete a local Git branch, follow these steps:
- Open a Git BASH window or Command Window in the root of your Git repository
- If necessary, use the git switch or checkout command to move off the branch you wish to delete
- Issue the
git branch --delete <branchname>
command to delete the local branch
- Run the git branch -a command to verify the local Git branch is deleted
Git Error: Cannot delete branch
One rule of local Git branch deletion is that you cannot delete a branch that is currently checked out. Otherwise, you run into the ‘cannot delete branch’ error as you can see in the example below:
[email protected] /c/local/branch (main) $ git branch -a * main new-branch old-branch
[email protected] /c/local/branch (main) $ git branch --delete main error: Cannot delete branch 'main' checked out at 'C:/git/delete'
In the above example, the user tried to delete the main Git branch while the it was checked out, which caused an error. However, deletion of the local Git branches named new-branch 0r old-branch would run without error:
[email protected] /c/local/branch (main) $ git branch --delete old-branch Deleted branch old-branch (was 44a55a1).
Delete local Git branch command
The command to delete a local git branch can take one of two forms:
- git branch –delete old-branch
- git branch -d old-branch
The only difference is the fact that the second local branch delete Git command uses an abbreviated syntax. Both commands do the exact same thing.
Remove vs local Git branch deletes
It should be noted that when you delete a local Git branch, the corresponding remote branch in a repository like GitHub or GitLab remains alive and active. Further steps must be taken to delete remote branches.
When you delete a local Git branch, the deletion will not be reflected in remote repos like GitHub or GitLab.
There can be a couple of scenarios wherein you would wish to delete branch. Following are some of the possible scenarios:
- Delete git branch locally
- Delete git branch remotely
- Delete git branch both locally and globally
- Perform git merge and Delete git branch
We will cover all these scenarios individually with the best recommendation to do this the right way.
Prepare Environment
I have setup my repository git_examples
using GitLab.
Following is my git version:
deepak@ubuntu:~/git_examples$ git --version
git version 2.32.0
I will clone my repository from gitlab to my local workstation:
deepak@ubuntu:~/git_examples$ git clone git@gitlab.com:golinuxcloud/git_examples.git
Git delete branch locally
If your branch is only available on your local workstation repository then you must follow this section. Currently I have following branch in the local repository of my workstation:
deepak@ubuntu:~/git_examples$ git branch
issue-5632
issue-6291
issue-9538
* main
my-feature-branch
To check the list of remote branches (i.e. branch which are available on the remote gitlab server):
deepak@ubuntu:~/git_examples$ git branch --remotes origin/HEAD -> origin/main origin/main origin/my-feature-branch
So the following branch are only present on my local workstation only but not on the remote:
issue-5632 issue-6291 issue-9538
Since these branches are not available on remote, so I just need to delete them locally.
ALSO READ: Git rebase explained in detail with examples
Scenario-1: Fix error: Cannot delete branch ‘XXX’ checked out at ‘YYY’
To delete a branch locally use the following command syntax:
git branch --delete|-d <local_branch_name>
First step, make sure you are not part of the branch which you wish to delete or else you will get this error:
deepak@ubuntu:~/git_examples$ git switch issue-6291 Switched to branch 'issue-6291' deepak@ubuntu:~/git_examples$ git branch --delete issue-6291 error: Cannot delete branch 'issue-6291' checked out at '/home/deepak/git_examples'
As you can see, I switched to issue-6291
branch and then trying to delete the same branch leads to an ERROR.
So to delete the branch, you must checkout as a different branch first.
deepak@ubuntu:~/git_examples$ git switch main
Switched to branch 'main'
Your branch is ahead of 'origin/main' by 2 commits.
(use "git push" to publish your local commits)
Check your current branch:
deepak@ubuntu:~/git_examples$ git branch
issue-5632
issue-6291
issue-9538
* main
my-feature-branch
Now try to delete your branch:
deepak@ubuntu:~/git_examples$ git branch --delete issue-6291
Deleted branch issue-6291 (was e126b0b).
Scenario-2: Fix error: The branch ‘XXX’ is not fully merged.
Let us try to delete another of our local branch:
deepak@ubuntu:~/git_examples$ git branch --delete issue-5632
error: The branch 'issue-5632' is not fully merged.
If you are sure you want to delete it, run ‘git branch -D issue-5632
‘. This error is caused because we have some un-merged changes in branch issue-5632
due to which the branch delete has failed.
ALSO READ: Git rename branch — local and remote (PROPERLY)
In such case either you can delete the branch forcefully or merge the changes and then perform the delete operation.
Solution-1: Perform merge and delete git branch
I will push these changes to a new branch issue-5632
on the remote gitlab server.
deepak@ubuntu:~/git_examples$ git push origin issue-5632
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (4/4), 319 bytes | 159.00 KiB/s, done.
Total 4 (delta 1), reused 0 (delta 0), pack-reused 0
remote:
remote: To create a merge request for issue-5632, visit:
remote: https://gitlab.com/golinuxcloud/git_examples/-/merge_requests/new?merge_request%5Bsource_branch%5D=issue-5632
remote:
To gitlab.com:golinuxcloud/git_examples.git
* [new branch] issue-5632 -> issue-5632
This will create a merge request with main branch and will also create a new branch on the remote server.
To merge this into main branch, switch to main
branch:
deepak@ubuntu:~/git_examples$ git switch main
Switched to branch 'main'
Your branch is ahead of 'origin/main' by 2 commits.
(use "git push" to publish your local commits)
Check your current branch
deepak@ubuntu:~/git_examples$ git branch
issue-5632
issue-9538
* main
my-feature-branch
Merge issue-5632 branch into main
deepak@ubuntu:~/git_examples$ git merge issue-5632
Updating e126b0b..cf00196
Fast-forward
test-5632/patch-1 | 0
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 test-5632/patch-1
Verify the git log to confirm the merge:
deepak@ubuntu:~/git_examples$ git log --oneline cf00196 (HEAD -> main, origin/issue-5632, issue-5632) Added patch-1 e126b0b (origin/my-feature-branch, my-feature-branch, issue-9538) Adding new group 5e04f57 Created new script to add groups 1b6369c (origin/main, origin/HEAD) Added create_users.sh script 6297a37 Updated script2.sh in main branch ...
Now you can go ahead and delete the local branch:
deepak@ubuntu:~/git_examples$ git branch --delete issue-5632
Deleted branch issue-5632 (was cf00196).
NOTE:
At this stage we have created a branch issue-5632 on the remote gitlab server as well which will still be present and need to be handled separately. We will cover this in next section of this article.
ALSO READ: git branch management with examples [Beginners]
Solution-2: Forcefully delete local branch
If you do not wish to merge your changes, then you can forcefully delete the branch locally using --delete --force
or -D
:
So you can use:
git branch --delete --force <branch_to_be_deleted>
OR
git branch -D <branch_to_be_deleted>
Git delete branch remotely
To delete a branch from the remote, use any of the following syntax:
git push origin --delete <branch> # Git version 1.7.0 or newer
git push origin -d <branch> # Shorter version (Git 1.7.0 or newer)
git push origin :<branch> # Git versions older than 1.7.0
Following are the list of remotely available branches on my gitlab server:
deepak@ubuntu:~/git_examples$ git branch --remotes origin/HEAD -> origin/main origin/issue-5632 origin/main origin/my-feature-branch
These are the list of locally available branch:
deepak@ubuntu:~/git_examples$ git branch
* issue-9538
main
my-feature-branch
Scenario-1: When branch is available only on the remote (not locally)
Since, issue-5632
branch is available only on the remote server as we have already deleted it on the local repo. To delete this branch also from the remote we will use:
deepak@ubuntu:~/git_examples$ git push origin --delete issue-5632
To gitlab.com:golinuxcloud/git_examples.git
- [deleted] issue-5632
Verify the list of branch on the remote to make sure your branch was deleted successfully:
deepak@ubuntu:~/git_examples$ git branch --remotes
origin/HEAD -> origin/main
origin/main
origin/my-feature-branch
ALSO READ: Move content from one git repo to another [5 simple steps]
Scenario-2: When there are un-merged changes locally
I have pushed issue-9538
to the remote gitlab server, so now this branch is also available on the remote:
deepak@ubuntu:~/git_examples$ git branch --remotes
origin/HEAD -> origin/main
origin/issue-9538
origin/main
origin/my-feature-branch
I will commit some changes into this branch, but will not merge it with main branch:
deepak@ubuntu:~/git_examples$ git branch * issue-9538 main my-feature-branch deepak@ubuntu:~/git_examples$ git add bugs/patch-9538 deepak@ubuntu:~/git_examples$ git commit -m "added patch for #9538" -a [issue-9538 d850184] added patch for #9538 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 bugs/patch-9538
Let’s try to delete this branch on the remote repo server:
deepak@ubuntu:~/git_examples$ git push origin --delete issue-9538
To gitlab.com:golinuxcloud/git_examples.git
- [deleted] issue-9538
So, even though I was in issue-9538
branch and there were un-merged changes, but still the remote branch was successfully deleted. So these factors do not matter if we wish to delete remote branch.
With this step, the remote branch has been deleted but the local branch is still there along with the un-merged changes:
deepak@ubuntu:~/git_examples$ git branch
* issue-9538
main
my-feature-branch
So we must delete this branch locally as explained in section one of this article.
Delete git branch both locally and remotely
We have covered this topic separately, now lets understand the flow which should be followed when trying to delete a branch from both local and remote git server.
ALSO READ: git undo commit before push [Practical Examples]
In my case my-feature-branch is available on both local and remote git server:
deepak@ubuntu:~/git_examples$ git branch
* issue-9538
main
my-feature-branch
Step-1: Switch to alternate branch
Make sure you are on a different branch and not in the one you plan to delete. To switch your branch you can use:
git checkout <different_branch>
OR
git switch <different_branch>
Since we are already on a different branch, we will ignore this step.
Step-2: Delete branch on the remote
Next we will delete the branch on the remote server first:
deepak@ubuntu:~/git_examples$ git push origin --delete my-feature-branch
To gitlab.com:golinuxcloud/git_examples.git
- [deleted] my-feature-branch
As you can verify, now my-feature-branch is deleted from remote but is still available locally:
deepak@ubuntu:~/git_examples$ git branch --all * issue-9538 main my-feature-branch remotes/origin/HEAD -> origin/main remotes/origin/main
Step-3: Delete branch locally
Now we can delete our branch locally. Since the remote branch is already deleted, we can safely use --delete --force
or -D
to perform a force delete of the git branch:
deepak@ubuntu:~/git_examples$ git branch --delete --force my-feature-branch
Deleted branch my-feature-branch (was e126b0b).
Verify the list of branch:
deepak@ubuntu:~/git_examples$ git branch --all * issue-9538 main remotes/origin/HEAD -> origin/main remotes/origin/main
Step-4: Pruning the obsolete local remote-tracking branch
Note that deleting X
remote branch from the command line using a git push
will also remove the local remote-tracking branch origin/X
, so it is necessary to prune the obsolete remote-tracking branch with git fetch --prune
or git fetch -p
.
deepak@ubuntu:~/git_examples$ git switch main
Switched to branch 'main'
Perform a fetch on other machines after deleting remote branch, to remove obsolete tracking branches.
deepak@ubuntu:~/git_examples$ git fetch --all --prune
Fetching origin
ALSO READ: First Time Git Setup | Git Config Global
Summary
In this article we discussed in depth about different commands using which you can delete git branch both locally and remotely. You can safely remove a branch with git branch -d yourbranch
. If it contains unmerged changes (ie, you would lose commits by deleting the branch), git will tell you and won’t delete it.
To delete a remote branch, use git push origin :mybranch
, assuming your remote name is origin and the remote branch you want do delete is named mybranch
.
Further Readings
git branch
Содержание
- Git delete branch — Are you doing it correctly?
- Prepare Environment
- Git delete branch locally
- Scenario-1: Fix error: Cannot delete branch ‘XXX’ checked out at ‘YYY’
- Scenario-2: Fix error: The branch ‘XXX’ is not fully merged.
- Solution-1: Perform merge and delete git branch
- Solution-2: Forcefully delete local branch
- Git delete branch remotely
- Scenario-1: When branch is available only on the remote (not locally)
- Scenario-2: When there are un-merged changes locally
- Delete git branch both locally and remotely
- Step-1: Switch to alternate branch
- Step-2: Delete branch on the remote
- Step-3: Delete branch locally
- Step-4: Pruning the obsolete local remote-tracking branch
- Summary
- Further Readings
- How to delete a Git branch locally
- How To Delete Local Branch In Git?
- List Local Branches
- Delete Local Branch
- Delete Local Branch Forcefully
- “error: Cannot delete branch ‘testing’ checked out at”
- Как удалить локальную и удаленную ветку Git
- Удалить локальную ветку Git
- Удалить удаленную ветку Git
- Выводы
Git delete branch — Are you doing it correctly?
Table of Contents
There can be a couple of scenarios wherein you would wish to delete branch. Following are some of the possible scenarios:
- Delete git branch locally
- Delete git branch remotely
- Delete git branch both locally and globally
- Perform git merge and Delete git branch
We will cover all these scenarios individually with the best recommendation to do this the right way.
Prepare Environment
I have setup my repository git_examples using GitLab.
Following is my git version:
I will clone my repository from gitlab to my local workstation:
Git delete branch locally
If your branch is only available on your local workstation repository then you must follow this section. Currently I have following branch in the local repository of my workstation:
To check the list of remote branches (i.e. branch which are available on the remote gitlab server):
So the following branch are only present on my local workstation only but not on the remote:
Since these branches are not available on remote, so I just need to delete them locally.
Scenario-1: Fix error: Cannot delete branch ‘XXX’ checked out at ‘YYY’
To delete a branch locally use the following command syntax:
First step, make sure you are not part of the branch which you wish to delete or else you will get this error:
As you can see, I switched to issue-6291 branch and then trying to delete the same branch leads to an ERROR.
So to delete the branch, you must checkout as a different branch first.
Check your current branch:
Now try to delete your branch:
Scenario-2: Fix error: The branch ‘XXX’ is not fully merged.
Let us try to delete another of our local branch:
If you are sure you want to delete it, run ‘ git branch -D issue-5632 ‘. This error is caused because we have some un-merged changes in branch issue-5632 due to which the branch delete has failed.
In such case either you can delete the branch forcefully or merge the changes and then perform the delete operation.
Solution-1: Perform merge and delete git branch
I will push these changes to a new branch issue-5632 on the remote gitlab server.
This will create a merge request with main branch and will also create a new branch on the remote server.
To merge this into main branch, switch to main branch:
Check your current branch
Merge issue-5632 branch into main
Verify the git log to confirm the merge:
Now you can go ahead and delete the local branch:
Solution-2: Forcefully delete local branch
If you do not wish to merge your changes, then you can forcefully delete the branch locally using —delete —force or -D :
Git delete branch remotely
To delete a branch from the remote, use any of the following syntax:
Following are the list of remotely available branches on my gitlab server:
These are the list of locally available branch:
Scenario-1: When branch is available only on the remote (not locally)
Since, issue-5632 branch is available only on the remote server as we have already deleted it on the local repo. To delete this branch also from the remote we will use:
Verify the list of branch on the remote to make sure your branch was deleted successfully:
Scenario-2: When there are un-merged changes locally
I have pushed issue-9538 to the remote gitlab server, so now this branch is also available on the remote:
I will commit some changes into this branch, but will not merge it with main branch:
Let’s try to delete this branch on the remote repo server:
So, even though I was in issue-9538 branch and there were un-merged changes, but still the remote branch was successfully deleted. So these factors do not matter if we wish to delete remote branch.
With this step, the remote branch has been deleted but the local branch is still there along with the un-merged changes:
So we must delete this branch locally as explained in section one of this article.
Delete git branch both locally and remotely
We have covered this topic separately, now lets understand the flow which should be followed when trying to delete a branch from both local and remote git server.
In my case my-feature-branch is available on both local and remote git server:
Step-1: Switch to alternate branch
Make sure you are on a different branch and not in the one you plan to delete. To switch your branch you can use:
Since we are already on a different branch, we will ignore this step.
Step-2: Delete branch on the remote
Next we will delete the branch on the remote server first:
As you can verify, now my-feature-branch is deleted from remote but is still available locally:
Step-3: Delete branch locally
Now we can delete our branch locally. Since the remote branch is already deleted, we can safely use —delete —force or -D to perform a force delete of the git branch:
Verify the list of branch:
Step-4: Pruning the obsolete local remote-tracking branch
Note that deleting X remote branch from the command line using a git push will also remove the local remote-tracking branch origin/X , so it is necessary to prune the obsolete remote-tracking branch with git fetch —prune or git fetch -p .
Perform a fetch on other machines after deleting remote branch, to remove obsolete tracking branches.
Summary
In this article we discussed in depth about different commands using which you can delete git branch both locally and remotely. You can safely remove a branch with git branch -d yourbranch . If it contains unmerged changes (ie, you would lose commits by deleting the branch), git will tell you and won’t delete it.
To delete a remote branch, use git push origin :mybranch , assuming your remote name is origin and the remote branch you want do delete is named mybranch .
Further Readings
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
to stay connected and get the latest updates
Источник
How to delete a Git branch locally
Community driven content discussing all aspects of software development from DevOps to design patterns.
- How to delete all Git branches except master or main . – TheServerSide.com
- How to rename and change a Git branch name locally &. – TheServerSide.com
- How to delete a Git repository – TheServerSide.com
Whether you use GitFlow, GitHub Flow or any other branch driven development strategy, you will inevitably end up with a local Git repository filled with branches you no longer need. Which is why it’s good to know the command to delete Git branches locally and permanently so they don’t pollute your local development environment.
To issue the command to delete a local Git branch, follow these steps:
- Open a Git BASH window or Command Window in the root of your Git repository
- If necessary, use the git switch or checkout command to move off the branch you wish to delete
- Issue the
command to delete the local branch
One rule of local Git branch deletion is that you cannot delete a branch that is currently checked out. Otherwise, you run into the ‘cannot delete branch’ error as you can see in the example below:
In the above example, the user tried to delete the main Git branch while the it was checked out, which caused an error. However, deletion of the local Git branches named new-branch 0r old-branch would run without error:
The command to delete a local git branch can take one of two forms:
- git branch –delete old-branch
- git branch -d old-branch
The only difference is the fact that the second local branch delete Git command uses an abbreviated syntax. Both commands do the exact same thing.
It should be noted that when you delete a local Git branch, the corresponding remote branch in a repository like GitHub or GitLab remains alive and active. Further steps must be taken to delete remote branches.
When you delete a local Git branch, the deletion will not be reflected in remote repos like GitHub or GitLab.
Enterprises increasingly rely on APIs to interact with customers and partners. It all starts with knowing which type of API is .
Although modern software systems can be inordinately complex, architects can still use simple napkin math to glean quick .
To establish the right development team size, managers must look at each member’s responsibilities and communication paths, as .
GitHub Actions required workflows and configuration variables can reduce duplicate configuration code and shore up policy .
Learn how low-code concepts and practices code can help enterprise developers be more efficient, create valuable apps more .
The rise of AI-assisted workflows will facilitate software development security amid growing open source vulnerabilities, but .
In 2023, companies expect to increase spending on public cloud applications and infrastructure, and hyperscalers that have .
EC2 instances that are improperly sized drain money and restrict performance demands on workloads. Learn how to right-size EC2 .
To add another level of security, find out how to automatically rotate keys within Azure key vault with step-by-step instructions.
Avast threat researchers detected exploitation of a Windows zero-day flaw in the wild, and organizations are being urged to patch.
Beneath the buzz around tech innovations at CES were discussions about cybersecurity and how to prevent the next generation of .
Enterprise cybersecurity hygiene must be a shared responsibility between employees and employers. Follow these steps to get the .
Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .
Источник
How To Delete Local Branch In Git?
Git provides the git branch -d command in order to delete the local branch in a git repository. This command accepts the branch name as a parameter which will be deleted. Keep in mind that this command only deletes the local branch and can not be used to delete the remote Git branch.
List Local Branches
Before deleting a branch we can list currently existing branches with the following git branch command. The currently active branch is expressed with the * which is master in the following example.
Delete Local Branch
The default way to delete a local branch in git is using the git branch -d . The -d option is used for delete operation. The long form of the -d option is —delete . The branch which will be deleted is added as a parameter like below. In the following example, we delete the branch named testing .
Alternatively, the log form delete option “–delete” can be used like below.
Delete Local Branch Forcefully
If the branch you want to delete contains commits that haven’t been merged to the local branches or pushed to the remote repository the -d or —delete option does not works. The local branch removal or delete operation can be forced with the -D option.
“error: Cannot delete branch ‘testing’ checked out at”
When we try to delete the currently active branch we get the “error: Cannot delete branch ‘testing’ checked out at” error. This error cause is the branch we want to delete locally is currently active. In order to solve this error and delete the local branch, we should switch to another branch.
So we use the git switch command by providing the branch name we want to switch. In this case, we use the master .
Now we can delete the local branch “testing” without a problem.
Источник
Как удалить локальную и удаленную ветку Git
Ветви — это часть повседневного процесса разработки и одна из самых мощных функций Git. После слияния ветвь она не служит никакой цели, кроме исторических исследований. Обычно рекомендуется удалять ветку после успешного слияния.
В этом руководстве рассказывается, как удалить локальные и удаленные ветки Git.
Удалить локальную ветку Git
Команда git branch позволяет вам перечислять, создавать , переименовывать и удалять ветки.
Чтобы удалить локальную ветку Git, вызовите команду git branch с параметром -d ( —delete ), за которым следует имя ветки:
Если вы попытаетесь удалить ветку, в которой есть не объединенные изменения, вы получите следующее сообщение об ошибке:
Как видно из сообщения выше, чтобы принудительно удалить ветку, используйте параметр -D который является ярлыком для —delete —force :
Обратите внимание: если вы удалите несоединенную ветку, вы потеряете все изменения в этой ветке.
Если вы попытаетесь удалить текущую ветку, вы получите следующее сообщение:
Вы не можете удалить ветку, в которой находитесь. Сначала переключитесь на другую ветку, а затем удалите branch_name :
Удалить удаленную ветку Git
В Git локальная и удаленная ветки — это отдельные объекты. Удаление локальной ветки не удаляет удаленную ветку.
Чтобы удалить удаленную ветку, используйте команду git push с параметром -d ( —delete ):
Где remote_name обычно origin :
Также существует альтернативная команда для удаления удаленной ветки, которую, по крайней мере, для меня запомнить сложнее:
Если вы работаете над проектом с группой людей и пытаетесь удалить удаленную ветку, которая уже удалена кем-то другим, вы получите следующее сообщение об ошибке:
В подобных ситуациях вам необходимо синхронизировать список веток с:
Параметр -p указывает Git перед загрузкой удалить все ссылки удаленного отслеживания, которые больше не существуют в удаленном репозитории.
Выводы
Мы показали вам, как удалить локальную и удаленную ветки Git. Ветви — это в основном ссылка на моментальный снимок ваших изменений и короткий жизненный цикл. После того, как ветка будет объединена с главной (или другой основной веткой), она больше не нужна, и ее следует удалить.
Если вы столкнулись с проблемой или хотите оставить отзыв, оставьте комментарий ниже.
Источник
Git provides the git branch -d
command in order to delete the local branch in a git repository. This command accepts the branch name as a parameter which will be deleted. Keep in mind that this command only deletes the local branch and can not be used to delete the remote Git branch.
List Local Branches
Before deleting a branch we can list currently existing branches with the following git branch
command. The currently active branch is expressed with the *
which is master in the following example.
$ git branch
The default way to delete a local branch in git is using the git branch -d
. The -d option is used for delete operation. The long form of the -d option is --delete
. The branch which will be deleted is added as a parameter like below. In the following example, we delete the branch named testing
.
$ git branch -d testing
Alternatively, the log form delete option “–delete” can be used like below.
$ git branch --delete testing
Delete Local Branch Forcefully
If the branch you want to delete contains commits that haven’t been merged to the local branches or pushed to the remote repository the -d
or --delete
option does not works. The local branch removal or delete operation can be forced with the -D
option.
$ git branch -D testing
“error: Cannot delete branch ‘testing’ checked out at”
When we try to delete the currently active branch we get the “error: Cannot delete branch ‘testing’ checked out at” error. This error cause is the branch we want to delete locally is currently active. In order to solve this error and delete the local branch, we should switch to another branch.
$ git branch -d testing
error: Cannot delete branch 'testing' checked out at
So we use the git switch
command by providing the branch name we want to switch. In this case, we use the master
.
$ git switch master
Now we can delete the local branch “testing” without a problem.
I am using Github and also SourceTree. I have made a git clone of my project.
Now when I try to delete a branch I made local, I face the following error:
git -c diff.mnemonicprefix=false -c core.quotepath=false branch -D develop
error: Cannot delete branch 'develop' checked out at 'C:/Users/näZAN/Documents/Protractor'
Completed with errors, see above.
Screenshot:
I am pretty new to working with branches, etc.
asked Dec 15, 2017 at 22:04
You cannot delete a branch that you are currently on.
If you want to delete the develop
branch, you’ll first need to create and switch to another one.
Note: This isn’t specific to Sourcetree; this is how git works.
answered Dec 15, 2017 at 22:11
0
One of the strongest features of Git is its lightweight branches. They allow you to work on parallel stages of development efficiently. A developer might even create individual branches for separate bugs. In both time and space, branches are almost without cost.
Many git workflows deal with both long-term and temporary branches. Therefore, there is often a need to delete branches during development. There is occasionally a need to delete shared branches, from a remote server, as well as local branches.
Why Delete a Branch?
First, if you’re still getting to grips with git, there’s a pretty good chance you’ll create a branch and then decide you didn’t need to. Or you might be experimenting with branches and wanting to clear up after yourself. This is fine since branching in git is a lightweight operation. It’s very fast and uses disk space efficiently.
As a result, many git development workflows encourage branching, even for very small or short tasks. For example, a common strategy is to create a branch for a single bug fix. This is true even if it involves just a single author making a one-line change in a single file.
For these reasons, creating and deleting branches are operations that need to be well understood. You might find yourself often deleting branches during a typical development workflow.
A Sample Repository With Branches
The following examples refer to a sample repository with the following structure:
$ git branch -vv
1 dev 1ae41e8 [origin/dev] first commit
2 * main 1ae41e8 [origin/main] first commit
Note that each local branch has a corresponding upstream branch from the remote: origin.
Deleting a Branch Using the Command Line
The basic command syntax for deleting a branch is:
git branch (-d | -D) [-r] <branchname>...
The simplest form of the command deletes a local branch, providing all its changes have been merged:
$ git branch -d dev
You can’t delete the branch that is currently active; if you try to do so, you’ll get a message like this:
error: Cannot delete branch 'main' checked out at '/tmp/sandbox'
When things go right, you’ll see a confirmation message:
Deleted branch dev (was 1ae41e8).
If you delete a branch that only exists locally, with unmerged changes, you’ll lose those changes. Therefore, git will refuse to delete a branch in such a situation, by default:
error: The branch ‘dev’ is not fully merged.
If you are sure you want to delete it, run 'git branch -D dev’.
As the error message informs, you can force deletion with the -D flag. However, git will allow you to delete an unmerged local branch if it exists remotely:
warning: deleting branch ‘dev’ that has been merged to
'refs/remotes/origin/dev’, but not yet merged to HEAD.
Deleted branch dev (was 9a6d20b).
Deleting a remote branch is quite different. You’ll use the git push command along with the -d flag to delete. After that, supply the name of the remote (often origin) and the branch name:
$ git push -d origin dev
To github.com:bobbykjack/sandbox.git
- [deleted] dev
Deleting Local and Remote Branches With GitHub Desktop
Unlike the command-line git program, GitHub’s desktop app will only let you delete the active branch. You can carry out this action via the Branch menu, by selecting the Delete option and confirming it:
GitHub Desktop won’t let you delete the default branch—e.g. main—even though git itself supports this. If the default branch is the one that is currently active, the app disables the menu action.
If the branch also represents a remote branch, GitHub Desktop gives the option of deleting it from the remote too:
Deleting Branches Using GitKraken
GitKraken displays your repository’s local and remote branches in the left-hand sidebar. You must delete each separately.
Hover over the appropriate branch name and click the Branch actions menu which looks like three vertical dots. From the menu, select Delete <branch name>:
You’ll see a confirmation message informing you that this is a destructive operation. You can confirm you want to continue with the Delete button:
Reflecting the default behavior of the git command-line program, you must first switch to a branch other than the one you’re deleting. Otherwise, you’ll see an error message:
Deleting Local and Remote Branches Using Tower
Deleting a branch with Tower is very similar to deleting a branch with GitKraken. Local and remote branches are shown in a panel on the left-hand side. Right-click on any branch and select the Delete option from the context menu:
One key difference is that a remote branch can be deleted along with its local branch, during confirmation:
Deleting a Branch on GitHub
GitHub only acts as a remote source, so branches there are remote by default. If you delete a branch using the GitHub website, you’ll have to delete the corresponding local branch using one of the other methods here.
As with the GitHub Desktop app, the GitHub website will not allow you to delete the default branch. The option simply does not appear. Deleting a branch is straightforward, though. From the repository’s Code page, click the branches link, locate the branch to delete, then click the Delete this branch icon, which looks like a trash can:
Be aware that there are no checks for unmerged changes, so on GitHub, the branch will simply be deleted immediately. However, since it will always represent a remote branch, this should be the behavior you’re expecting.
Note that, after deleting, you’ll see a button to Restore the branch. However, this is simply a useful undo feature, in case you click the delete icon accidentally. Do not rely on it, because as soon as you refresh or navigate away from the page, you’ll lose the option!
Deleting Local and Remote Branches on Bitbucket
Bitbucket, like GitHub, will not allow you to delete the default branch. Bitbucket calls this the Main branch in Repository settings. You can delete any other branch listed on the Branches tab, via its corresponding Actions menu:
You can also delete more than one branch at once if you’re doing a big cleanup operation:
Deleting Branches Is Part of a Typical Git Workflow
Git branches can complicate your workflow, especially one with local, remote, and tracking branches. But for simple day-to-day development, you’re likely to be creating and deleting local branches all the time. This is a core aspect of a typical git workflow you should become accustomed to.
Ветви — это часть повседневного процесса разработки и одна из самых мощных функций Git. После слияния ветвь она не служит никакой цели, кроме исторических исследований. Обычно рекомендуется удалять ветку после успешного слияния.
В этом руководстве рассказывается, как удалить локальные и удаленные ветки Git.
Удалить локальную ветку Git
Команда git branch
позволяет вам перечислять, создавать , переименовывать и удалять ветки.
Чтобы удалить локальную ветку Git, вызовите команду git branch
с параметром -d
( --delete
), за которым следует имя ветки:
git branch -d branch_name
Deleted branch branch_name (was 17d9aa0).
Если вы попытаетесь удалить ветку, в которой есть не объединенные изменения, вы получите следующее сообщение об ошибке:
error: The branch 'branch_name' is not fully merged.
If you are sure you want to delete it, run 'git branch -D branch_name'.
Как видно из сообщения выше, чтобы принудительно удалить ветку, используйте параметр -D
который является ярлыком для --delete --force
:
git branch -D branch_name
Обратите внимание: если вы удалите несоединенную ветку, вы потеряете все изменения в этой ветке.
Чтобы вывести список всех ветвей, содержащих не объединенные изменения, используйте команду git branch --no-merged
.
Если вы попытаетесь удалить текущую ветку, вы получите следующее сообщение:
error: Cannot delete branch 'branch_name' checked out at '/path/to/repository'
Вы не можете удалить ветку, в которой находитесь. Сначала переключитесь на другую ветку, а затем удалите branch_name
:
git checkout master
git branch -d branch_name
Удалить удаленную ветку Git
В Git локальная и удаленная ветки — это отдельные объекты. Удаление локальной ветки не удаляет удаленную ветку.
Чтобы удалить удаленную ветку, используйте команду git push
с параметром -d
( --delete
):
git push remote_name --delete branch_name
Где remote_name
обычно origin
:
git push origin --delete branch_name
...
- [deleted] branch_name
Также существует альтернативная команда для удаления удаленной ветки, которую, по крайней мере, для меня запомнить сложнее:
git push origin remote_name :branch_name
Если вы работаете над проектом с группой людей и пытаетесь удалить удаленную ветку, которая уже удалена кем-то другим, вы получите следующее сообщение об ошибке:
error: unable to push to unqualified destination: branch_name The destination refspec neither matches an existing ref on the remote nor begins with refs/, and we are unable to guess a prefix based on the source ref. error: failed to push some refs to '[email protected]:/my_repo'
В подобных ситуациях вам необходимо синхронизировать список веток с:
git fetch -p
Параметр -p
указывает Git перед загрузкой удалить все ссылки удаленного отслеживания, которые больше не существуют в удаленном репозитории.
Выводы
Мы показали вам, как удалить локальную и удаленную ветки Git. Ветви — это в основном ссылка на моментальный снимок ваших изменений и короткий жизненный цикл. После того, как ветка будет объединена с главной (или другой основной веткой), она больше не нужна, и ее следует удалить.
Если вы столкнулись с проблемой или хотите оставить отзыв, оставьте комментарий ниже.