Ferrybig
Ferrybig

Reputation: 18834

Checkout to a local branch as detached a head

I'm trying to checkout to the latest commit of a git branch in the way that git thinks its detached. I cannot checkout to the branch itself because a git worktree prevents this interaction, and bypassing this using the -f.

$ mkdir temp1
$ cd temp1
$ git init
$ echo a > test.txt
$ git add test.txt
$ git commit -m "Initial commit"
$ git worktree add ../temp2 --no-checkout
$ cd ../temp2
$ git checkout master
fatal: 'master' is already checked out at '../temp1'

While inside the "temp2" repository, I can checkout manually to the commit using its hash (git checkout 392847), I want to automate this without typing git log, copying the id, and then pasting it inside the git checkout command line.

Example what I want: (similar to a git checkout origin/master for repositories that contain pushed work):

$ git checkout <magic prefix> master
Note: checking out '<magic prefix>/master'.    

You are in 'detached HEAD' state. You can look around, make experimental                                                
changes and commit them, and you can discard any commits you make in this                                               
state without impacting any branches by performing another checkout.  

If you want to create a new branch to retain commits you create, you may                                                
do so (now or later) by using -b with the checkout command again. Example:                                                                                                                                                                        

    git checkout -b <new-branch-name>                                       

Upvotes: 1

Views: 67

Answers (2)

Vladimir Panteleev
Vladimir Panteleev

Reputation: 25187

How about:

$ git checkout --detach master

This will effectively resolve the commit SHA1 of the master branch, then check it out as a detached HEAD. Alternative ways to do the same thing are git checkout $(git rev-parse master), or the shorter git checkout master^0.

Alternatively, you could always create a new branch pointing to the same commit (git checkout -b master-copy master), or use a full clone (git clone temp1 temp2).

Upvotes: 1

Mark Adelsberger
Mark Adelsberger

Reputation: 45649

The easiest way is git checkout --detach master

Upvotes: 0

Related Questions