简体   繁体   中英

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

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?

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

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.

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

If is not found but there does exist a tracking branch in exactly one remote (call it ) 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 .

The git switch guess mode applies to remote tracking branches, meaning branches fetched into the origin namespace in your local repository.

Deleting the branch on Github would not delete the remote tracking branch in your local repository, hence a git fetch --prune mentioned by Berkay Berabi 's answer .
Or at least (as in here ):

git branch -d origin/AB-10/add_flights

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM