Switch Git branch without files checkout
Yes, you can do this.
git symbolic-ref HEAD refs/heads/otherbranch
If you need to commit on this branch, you'll want to reset the index too otherwise you'll end up committing something based on the last checked out branch.
git reset
Using basic git commands only:
This answer is a bit longer than that of Charles, but it consists solely of basic git commands that I can understand and thus remember, eliminating the need to keep looking it up.
Mark your current location (commit first if needed):
git checkout -b temp
Reset (moves) the marker to the other branch without changing working dir:
git reset <branch where you want to go>
now temp and other branch point to the same commit, and your working dir is untouched.
git checkout <branch where you want to go>
since your HEAD is already pointing to the same commit, working dir is not touched
git branch -d temp
Note that these commands are also readily available from any graphical client.
In v2.24
git switch
is something like a safegit checkout
.
Hence I renamed the alias below togit hop
for
"hop on the branch without changing worktree"
For the benefit of the reader:
While I think that Charles Bailey's solution is a correct one, this solution needs a tweak when switching to something, which is not a local branch. Also there should be some way how to do it with regular commands which is easy to understand. Here is what I came up with:
git checkout --detach
git reset --soft commitish
git checkout commitish
Explained:
-
git checkout --detach
is the same asgit checkout HEAD^{}
which leaves the current branch behind and goes into "detached head state". So the next modification ofHEAD
no more affects any branch. DetachingHEAD
does not affect the worktree nor the index. -
git reset --soft commitish
then movesHEAD
to the SHA of the givencommitish
. If you want to update the index, too, leave--soft
away, but I do not recommend to do so. This, again, does not touch the worktree, and (--soft
) not the index. -
git checkout commitish
then attachesHEAD
to the givencommitish
(branch) again. (Ifcommitish
is a SHA nothing happens.) This, too, does not affect index nor worktree.
This solution accepts everything which refers to a commit, so this is ideal for some git
alias. The rev-parse
below is just a test to make sure, nothing breaks in the chain, such that typos do not accidentally switch into detached head state (error recovery would be way more complex).
This leads to following git hop treeish
alias:
git config --global alias.hop '!f() { git rev-parse --verify "$*" && git checkout "HEAD^{}" && git reset --soft "$*" && git checkout "$*"; }; f'
FYI, you can find it in my list of git
aliases.
Wouldn't be a better solution to have two working directories (two working areas) with one repository, or even two repositories?
There is git-new-workdir tool in contrib/
section to help you with this.