Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git how to checkout a commit of a branch

Tags:

git

How can I check out a commit version of a branch in git?

For example, my branch, Dev, has a commit ad4f43af43e. How can I check out that commit? Not just a single file, but a whole branch.

I searched online and found: git checkout <commit>, but it didn't specify branch name

like image 590
user1615666 Avatar asked Feb 10 '17 12:02

user1615666


People also ask

How do you checkout a commit as a branch?

To pull up a list of your commits and their associated hashes, you can run the git log command. To checkout a previous commit, you will use the Git checkout command followed by the commit hash you retrieved from your Git log.


3 Answers

git checkout <hash>         # non named commit
git checkout <branch_name>  # named commit

The two lines above will place the HEAD pointer on the given commit. You should know that a branch name is a commit, except it can evolve if a new commit is added when you're on that branch.

If you want to place your branch Dev on the commit ad4f43af43e you can do this

git branch -f Dev ad4f43af43e

Be careful! This is dangerous because you may lose commits.

like image 198
smarber Avatar answered Oct 13 '22 03:10

smarber


If you're looking to branch out from a specific commit of a branch, first be sure you are in the branch,

git checkout dev

Now I want to checkout a specific commit 123654 from the dev branch to a new branch while keeping the head on main branch.

git checkout -b new-branch 123654
like image 39
myselfmiqdad Avatar answered Oct 13 '22 02:10

myselfmiqdad


You can checkout to the commit-sha then, create a new branch (say, feature) from that commit.

$ git checkout <commit>
$ git checkout -b feature    # create a new branch named `feature` from the commit


# if you want to replace the current branch (say 'develop') with new created branch ('feature') 
$ git branch -D develop     # delete the local 'develop' branch
$ git checkout -b develop   # create a new 'develop' branch from 'feature' branch 
like image 44
Sajib Khan Avatar answered Oct 13 '22 02:10

Sajib Khan