Error cannot delete branch master checked out at

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

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's user avatar

j08691

201k31 gold badges257 silver badges270 bronze badges

asked Jan 5, 2017 at 18:35

Bob Wakefield's user avatar

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 Aggarwal's user avatar

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

jinxcat2008's user avatar

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

Randy Leberknight's user avatar

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

dkniffin's user avatar

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's user avatar

ggorlen

40k7 gold badges66 silver badges89 bronze badges

answered Sep 6, 2019 at 12:23

Sankar Natarajan's user avatar

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

Raskul's user avatar

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

APartha77's user avatar

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

Fermat's Little Student's user avatar

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

Vasu's user avatar

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 Hobbelt's user avatar

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 Mitta's user avatar

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 s's user avatar

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

Toxic Xander's user avatar

git branch --D branch-name

Please run this code to delete

answered Oct 31, 2022 at 6:15

Mubashar Hussain's user avatar

Содержание

  1. Git delete branch — Are you doing it correctly?
  2. Prepare Environment
  3. Git delete branch locally
  4. Scenario-1: Fix error: Cannot delete branch ‘XXX’ checked out at ‘YYY’
  5. Scenario-2: Fix error: The branch ‘XXX’ is not fully merged.
  6. Solution-1: Perform merge and delete git branch
  7. Solution-2: Forcefully delete local branch
  8. Git delete branch remotely
  9. Scenario-1: When branch is available only on the remote (not locally)
  10. Scenario-2: When there are un-merged changes locally
  11. Delete git branch both locally and remotely
  12. Step-1: Switch to alternate branch
  13. Step-2: Delete branch on the remote
  14. Step-3: Delete branch locally
  15. Step-4: Pruning the obsolete local remote-tracking branch
  16. Summary
  17. Further Readings
  18. How to delete a Git branch locally
  19. How To Delete Local Branch In Git?
  20. List Local Branches
  21. Delete Local Branch
  22. Delete Local Branch Forcefully
  23. “error: Cannot delete branch ‘testing’ checked out at”
  24. Как удалить локальную и удаленную ветку Git
  25. Удалить локальную ветку Git
  26. Удалить удаленную ветку Git
  27. Выводы

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:

  1. Delete git branch locally
  2. Delete git branch remotely
  3. Delete git branch both locally and globally
  4. 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:

  1. Open a Git BASH window or Command Window in the root of your Git repository
  2. If necessary, use the git switch or checkout command to move off the branch you wish to delete
  3. Issue the

command to delete the local branch

  • Run the git branch -a command to verify the local Git branch is deleted
  • 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. Ветви — это в основном ссылка на моментальный снимок ваших изменений и короткий жизненный цикл. После того, как ветка будет объединена с главной (или другой основной веткой), она больше не нужна, и ее следует удалить.

    Если вы столкнулись с проблемой или хотите оставить отзыв, оставьте комментарий ниже.

    Источник

    There can be a couple of scenarios wherein you would wish to delete branch. Following are some of the possible scenarios:

    1. Delete git branch locally
    2. Delete git branch remotely
    3. Delete git branch both locally and globally
    4. 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 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
    List Local Branches

    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.

    “error: Cannot delete branch ‘testing’ checked out at”

    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:

    1. Open a Git BASH window or Command Window in the root of your Git repository
    2. If necessary, use the git switch or checkout command to move off the branch you wish to delete
    3. Issue the
      git branch --delete <branchname>

      command to delete the local branch

    4. 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.

    git no upstream branch error fix

    When you delete a local Git branch, the deletion will not be reflected in remote repos like GitHub or GitLab.

    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.

    Scott - Слава Україні's user avatar

    asked Dec 15, 2017 at 22:04

    XsiSec's user avatar

    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

    Ветви — это часть повседневного процесса разработки и одна из самых мощных функций 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 mastergit 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. Ветви — это в основном ссылка на моментальный снимок ваших изменений и короткий жизненный цикл. После того, как ветка будет объединена с главной (или другой основной веткой), она больше не нужна, и ее следует удалить.

    Если вы столкнулись с проблемой или хотите оставить отзыв, оставьте комментарий ниже.

    1. Overview

    Git has been widely used as the version control system in the industry. Further, Git branches are a part of our everyday development process.

    In this tutorial, we’ll explore how to delete Git branches.

    2. Preparation of the Git Repository

    To easier address how to delete a Git branch, let’s first prepare a Git repository as an example.

    First, let’s clone the myRepo repository (https://github.com/sk1418/myRepo) from GitHub for testing:

    $ git clone [email protected]:sk1418/myRepo.git
    Cloning into 'myRepo'...
    ...
    remote: Total 6 (delta 0), reused 3 (delta 0), pack-reused 0
    Receiving objects: 100% (6/6), done

    Second, let’s enter the local myRepo directory and check the branches:

    $ git branch -a
    * master
      remotes/origin/HEAD -> origin/master
      remotes/origin/master
    

    As we can see from the output above, currently, we have only one master branch in the myRepo repository. Also, the master branch is myRepo‘s default branch.

    Next, let’s create some branches and show how to delete a branch locally and remotely. In this tutorial, we’ll focus on deleting branches in the command line.

    3. Deleting a Local Branch

    Let’s first have a look at deleting a local branch.

    Git’s git branch command has two options for deleting a local branch: -d and -D.

    Next, let’s take a closer look at them and understand the difference between these two options through an example.

    3.1. Deleting a Local Branch With the -d Option

    First, let’s try to create a local branch:

    $ git checkout -b feature
    Switched to a new branch 'feature'

    Next, let’s delete the feature branch using the -d option:

    $ git branch -d feature
    error: Cannot delete branch 'feature' checked out at '/tmp/test/myRepo'

    Oops, as we can see, we’ve got an error message. This is because we’re currently on the feature branch:

    $ git branch
    * feature
      master

    In other words, we cannot delete a currently checked-out branch. So, let’s switch to the master branch and fire the command again:

    $ git checkout master
    Switched to branch 'master'
    Your branch is up to date with 'origin/master'.
    $ git branch -d feature
    Deleted branch feature (was 3aac499)
    
    $ git branch -a
    * master
    remotes/origin/HEAD -> origin/master
    remotes/origin/master

    As we can see, we’ve deleted the local feature branch successfully.

    3.2. Deleting a Local Branch With the -D Option

    First, let’s create the feature branch again. But this time, we’re going to make some changes and commit it:

    $ git checkout -b feature
    Switched to a new branch 'feature'
    
    # ... modify the README.md file ...
    $ echo "new feature" >> README.md
    $ git status
    On branch feature
    Changes not staged for commit:
    ...
    	modified:   README.md
    
    no changes added to commit (use "git add" and/or "git commit -a")
    
    $ git ci -am'add "feature" to the readme'
    [feature 4a87db9] add "feature" to the readme
     1 file changed, 1 insertion(+)

    Now, Git will refuse to delete the feature branch if we still use the -d option:

    $ git checkout master
    Switched to branch 'master'
    Your branch is up to date with 'origin/master'.
    
    $ git branch -d feature
    error: The branch 'feature' is not fully merged.
    If you are sure you want to delete it, run 'git branch -D feature'.

    This is because the to-be-deleted branch (feature) is ahead of the default branch (master):

    $ git log --graph --abbrev-commit 
    * commit 4a87db9 (HEAD -> feature)
    | Author: ...
    | Date:   ...| 
    |     add "feature" to the readme
    | 
    * commit 3aac499 (origin/master, origin/HEAD, master)
    | Author: ...
    | Date:   ...| 
    |     the first commit
    | 
    * commit e1ccb56
      Author: ...
      Date:   ...  
          Initial commit
    

    There are two ways to solve the problem. First, we can merge the feature branch into master and then execute “git branch -d feature” again.

    However, if we want to discard the unmerged commits, as the error message suggested, we can run “git branch -D feature” to execute a force deletion:

    $ git branch -D feature
    Deleted branch feature (was 4a87db9)
    
    $ git branch -a
    * master
    remotes/origin/HEAD -> origin/master
    remotes/origin/master.

    3.3. git branch -d/-D Won’t Delete the Remote Branch

    So far, we’ve deleted a local branch using git branch with the -d and -D options. It’s worth mentioning that no matter whether we delete with -d or -D, this command will only remove the local branch. No remote branch will be deleted, even if the deleted local branch is tracking a remote branch.

    Next, let’s understand this through an example. Again, let’s create a feature branch, make some changes, and push the commit to the remote repository:

    $ git checkout -b feature
    Switched to a new branch 'feature'
    
    # add a new file
    $ echo "a wonderful new file" > wonderful.txt
    
    $ git add . && git ci -am'add wonderful.txt'
    [feature 2dd012d] add wonderful.txt
     1 file changed, 1 insertion(+)
     create mode 100644 wonderful.txt
    $ git push
    ...
    To github.com:sk1418/myRepo.git
     * [new branch]      feature -> feature

    As the output above shows, we’ve created a new file, wonderful.txt, on the feature branch and pushed the commit to the remote repository.

    Therefore, the local feature branch is tracking the remote feature branch:

    $ git remote show origin | grep feature
        feature tracked
        feature pushes to feature (up to date)

    Since we haven’t merged feature into master, let’s delete the local feature branch with the -D option:

    $ git checkout master
    Switched to branch 'master'
    Your branch is up to date with 'origin/master'.
    
    $ git branch -D feature
    Deleted branch feature (was 2dd012d).
    
    $ git branch -a
    * master
      remotes/origin/HEAD -> origin/master
      remotes/origin/feature
      remotes/origin/master

    As we can see in the output of the command git branch -a, the local feature branch is gone. But the /remotes/origin/feature branch is not removed.

    Now, if we check out the feature branch again, the changes we’ve made are still there:

    $ git checkout feature
    Switched to branch 'feature'
    Your branch is up to date with 'origin/feature'.
    $ cat wonderful.txt 
    a wonderful new file
    

    Next, let’s see how to remove a remote branch.

    4. Deleting a Remote Branch

    We can use the command git push origin :<branchName> to remove a remote branch if our Git version is before 1.7.0. However, this command doesn’t look like a deletion operation. Therefore, since version 1.7.0, Git has introduced the git push origin -d <branchName> command to delete a remote branch. Apparently, this command is easier to understand and memorize than the older version.

    Just now, we’ve deleted the local branch feature, and we’ve seen that the remote feature branch is still there. So now, let’s use the mentioned command to remove the remote feature branch.

    Before we delete the remote feature, let’s first create a local feature branch to track the remote one. This is because we want to check if removing a remote branch will impact the tracking of local branches:

    $ git checkout feature 
    branch 'feature' set up to track 'origin/feature'.
    Switched to a new branch 'feature'
    $ git branch -a
    * feature
      master
      remotes/origin/HEAD -> origin/master
      remotes/origin/feature
      remotes/origin/master

    So, now we have the local and remote feature branches. Further, we’re currently on the local feature branch.

    Next, let’s remove the remote feature branch:

    $ git push origin -d feature
    To github.com:sk1418/myRepo.git
     - [deleted]         feature
    $ git branch -a
    * feature
      master
      remotes/origin/HEAD -> origin/master
      remotes/origin/master
    

    As we can see, after we execute the git push -d feature command, the remote feature branch has been deleted. However, the local feature branch is still there. That is to say, deleting a remote branch won’t impact the local tracking branches. Therefore, if we launch git push now, the local feature branch will be pushed to remote again.

    Moreover, unlike the local branch deletion, we can delete a remote branch no matter which local branch we’re currently working on. In the example above, we’re on the local feature branch, but we can still remove the remote feature branch without any problem.

    5. Conclusion

    In this article, we’ve explored how to delete Git’s local and remote branches using commands.

    Let’s summarize them quickly:

    • Delete a local branch: git branch -d/-D <branchName> (the -D option is for force deletion)
    • Delete a remote branch: git push origin -d <branchName> or git push origin :<branchName>

    Also, we’ve understood that removing a branch on a local or remote will not impact the branches on the other side.

    Удаление локальной ветки

    Чтобы удалить локальную ветку в Git нужно выполнить команду (вместо mybranch необходимо поставить название ветки, которую вы хотите удалить):

    git branch -d mybranch

    Обратите внимание на то, что ветка, которую вы удаляете, не должна быть вашей текущей веткой, в которой вы работаете, иначе отобразится ошибка вида:
    error: Cannot delete branch ’mybranch’ checked out at ’/path/to
    Поэтому, если вам нужно удалить текущую ветку, то сначала нужно переключиться на какую-либо другую ветку, а только потом выполнять удаление.

    Если вдруг возникает ошибка: The branch ’mybranch’ is not fully merged. If you are sure you want to delete it и вы по прежнему хотите удалить ветку, то для принудительного удаления ветки можно воспользоваться опцией -D:

    git branch -D mybranch

    Удаление удаленной ветки

    Чтобы удалить удаленную (remote) ветку используется команда (вместо origin и mybranch необходимо поставить свои данные):

    git push origin --delete mybranch

    Вместо —delete можно просто писать -d:

    git push origin -d mybranch

    Смотрите также:

    • Как изменить файлы в старом коммите (не последнем)
    • Как добавить все файлы в коммит, кроме одного
    • Как создать ветку из предыдущего коммита
    • Команда Git stash. Как прятать изменения в Git
    • Как показать файлы, которые будут добавлены в текущий коммит
    • Как переименовать ветку
    • Как показать текущую ветку
    • Как создать новую ветку

    Понравилась статья? Поделить с друзьями:
  • Error cannot declare member function to have static linkage
  • Error cannot create video capture filter микроскоп
  • Error cannot create soundtoys version root folder at soundtoys 5
  • Error cannot create service zabbix agent 0x00000430
  • Error cannot create file xampp control ini