Home > Blockchain >  Git: Why I can still switch to a branch after deletion?
Git: Why I can still switch to a branch after deletion?

Time:08-09

I have just noticed that I can still switch back to a branch after deleting it. Here is a particular example that I have:

git switch master
git branch -d AB-10/add_flights
...
// deleting also the remote branch on GitHub

git switch AB-10/add_flights

// I see the branch again

How come?

CodePudding user response:

The reason is simple: you deleted it only locally.

Man page reports:

Optionally a new branch could be created with either -c, -C, automatically from a remote branch of same name (see --guess), or detach the working tree from any branch with
       --detach, along with switching.

Due to the fact that it still exists in remote, GIT can switch to it again.

Remove it by git push --delete origin <branch-name> then try again to check it...

CodePudding user response:

git switch is a newly introduced command to take some burden from git checkout.

According to the manual of git checkout,

git checkout [<branch>]

To prepare for working on <branch>, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch. Local modifications to the files in the working tree are kept, so that they can be committed to the <branch>.

If is not found but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name and --no-guess is not specified, treat as equivalent to

$ git checkout -b <branch> --track <remote>/<branch>

So after you delete the branch and run git checkout <branch>, it's created from <remote>/<branch> again.

It also applies to git switch.

CodePudding user response:

A good practice is to prune after you have deleted the remote and local branch, you can do

git fetch --prune

This will delete all the local copies for which the remote branch is deleted.

From the man page:

   -p, --prune
       Before fetching, remove any remote-tracking references that no longer exist on the remote.
       Tags are not subject to pruning if they are fetched only because of the default tag
       auto-following or due to a --tags option. However, if tags are fetched due to an explicit
       refspec (either on the command line or in the remote configuration, for example if the
       remote was cloned with the --mirror option), then they are also subject to pruning.
       Supplying --prune-tags is a shorthand for providing the tag refspec.
  • Related