Home > Software design >  Git checkout tag exisiting branch
Git checkout tag exisiting branch

Time:10-20

There is a tag 1.2 and a branch exp.

I can checkout the tag by git checkout 1.2 and it brings me in the detached head state which is fine. There is already a branch I have created on the server = exp. The branch exp is based on the master. As of now master (thus also exp) are two commits ahead of 1.2.

What I would like to do is start at 1.2 and retain all my future commits to the branch exp.

However, when I do

git checkout 1.2 -b exp

I get an error

fatal: a branch named 'exp' already exists

I understand the logic behind this and I realize the practice is to create a new branch.

What I essentially want is to use the existing branch name exp and not create a new branch. I don't care about if exp is ahead or behind 1.2

As an example, the following timeline:

  • t = 0 --> checked out 1.2

  • t = 1 --> add new code to tag 1.2. All this new code must sit on the existing branch exp because I cannot commit on the tag.

t = 0 is clear for me but t = 1 is not.

CodePudding user response:

fatal: a branch named 'exp' already exists

There is a solution to this which is shockingly simple: delete the existing branch.

A branch in git has effectively zero metadata, it's just a name referencing a commit. Committing "on" a branch just points the same name at a new commit. If you want to point that name somewhere else, just discard the old reference and create a new one:

git branch -D exp
git checkout 1.2 -b exp

Note that the "1.2" here is just standing in for "the commit which is pointed at by the tag 1.2" - what you're really specifying is "point the new branch exp at this existing commit".

There are other ways of achieving the same thing; the simplest is to use git checkout -B instead of git checkout -b as documented here:

git checkout 1.2 -B exp

That said, if your git is not too old, you should get used to using git switch and git restore which are more intuitive commands for various things that git checkout and git reset do. The equivalent in that case is git switch -C or git switch --force-create:

git switch -C exp 1.2
  •  Tags:  
  • git
  • Related