Clone git repository with specific revision
This post will discuss how to clone a git repository with a specific revision.
1. git fetch
To clone a specific revision of a Git repository, it’s best to avoid git-clone since git-clone clones the full repository. The recommended solution is to fetch the specific branch that you want to clone with git-fetch
. Here are the complete steps:
git init
# add a remote named origin for the repository at <repository>
git remote add origin <repository>
# fetch a commit using its hash
git fetch origin <commit-hash>
# reset repository to that commit
git reset --hard FETCH_HEAD
This approach is demonstrated below:
2. git clone
For small repositories, you can use the git-clone
to easily reset the repository to any specific commit with git-reset, as demonstrated below:
git clone <repository> .
# hard reset repository to a specific commit
git reset --hard <commit-hash>
This assumes you’re on the master branch. To again go back to the most recent commit, you can simply do a git-pull
. This is demonstrated below:
Alternatively, you can perform git-clone
and then check out a specific revision with git-checkout.
git clone <repository> .
# checkout a commit using its hash
git checkout <commit-hash>
# hard reset repository
git reset --hard
This approach is demonstrated below:
That’s all about cloning a Git repository with a specific revision.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)