Git Chekout Takes Sha Instead Of Branch

Nahum Litvin
2 min readNov 26, 2020

Was debugging a weird production issue. the version deploy was absolutely wrong.

Premise:

When our CI build the product it creates a branch. with the build number. in our CI it was a running integer but in the repo I created for the example it will be 2c4f227

by coincidence it was starting the same way as a random commit on the main branch.

on the deploy stage we clone the repo (on main branch by default)

git clone git@github.com:NahumLitvin/GitTakesShaInsteadOfRemoteBranch.git

git checkout 2c4f227

and thats the result I got:

Note: checking out ‘2c4f227’.

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>

HEAD is now at 2c4f227 Initial commit

git checked out the commit 2c4f227 instead of the branch 2c4f227!

Solution:

git checkout origin/2c4f227

will checkout the correct branch

another more concise way is to use the new git switch command available from git 2.29.0

git switch

git switch 2c4f227
warning: refname ‘2c4f227’ is ambiguous.
Switched to branch ‘2c4f227’
Your branch is up to date with ‘origin/2c4f227’.

git switch will ‘Switch to a specified branch. The working tree and the index are updated to match the branch. All new commits will be added to the tip of this branch.’
when:
git checkout ‘Updates files in the working tree to match the version in the index or the specified tree. If no pathspec was given, git checkout will also update HEAD to set the specified branch as the current branch.’

additional reading

see this stack overflow Q&A for a better explanation: https://stackoverflow.com/questions/57123031/git-checkout-commit-hash-vs-git-checkout-branch/

--

--