I'm trying to find a simple command to checkout a tag and preserve the branch name from where the tag belongs to. I am aware that tags are not necessarily attached to branches but rather commits. I'm also aware that I could achieve this in multiple commands, like:
- Find branch name by parsing out response from:
git branch -a --contains <tag>
. git fetch
.git switch <branch-name-found-in-step-1>
.
But since you don't know what you don't know, I'm wondering if there's a one-line command to achieve this, something like: git switch --tag <tag>
that automagically does what I want. If something like that does not exist, what would be the simplest way to accomplish what I'm looking for?
CodePudding user response:
Here is a shot at a one liner:
git switch -C $(git branch -r --format="%(refname:lstrip=3)" --contain <tag>) <tag>
Some explanations:
git branch -r ...
: only list remote branches, do not mix local and remote if some local branches were already present--format="%(refname:lstrip=3)"
: remove the leftmost 3 chunks from the full ref name for a remote branch :refs/remotes/origin/<keep only that part>
git switch -C <branch> <tag>
: if for some reason a local<branch>
already existed in your repo,git switch <branch>
would switch to that branch, in its current state. With-C
(uppercaseC
) and<tag>
, you will always have a branch pointing at<tag>
.