How to Git Clone a Specific Commit |Video upload date:  · Duration: PT11M23S  · Language: EN

Step by step guide to fetch a single commit from GitHub or GitLab using fetch and checkout with shallow and sparse options

Why you might do this

Want a single commit from a repo without cloning the whole archaeological dig of history That is understandable and efficient and a little bit smug This guide shows the practical git commands to fetch one commit and work with it locally whether the host is GitHub or GitLab

Find the commit hash

Open the commit in the web UI or use git log on a clone you already have Copy the full SHA to avoid surprises with similar prefixes The full SHA is your friend

Prepare a local repository and add the remote

Start fresh so you do not accidentally pull centuries of history

git init
git remote add origin REPO_URL

Fetch the single commit with shallow depth

Ask the server for the object you want and no more This uses a depth of 1 so the server sends only the single commit object if it can

git fetch --depth 1 origin COMMIT_HASH

Notes on shallow fetch

  • Some hosts let you fetch by raw commit SHA and some do not
  • If the server accepts the request you will get FETCH_HEAD pointing at the fetched object

Checkout the fetched commit into a branch

Detach your inner panic and give git a branch so tools behave normally

git checkout -b single-commit FETCH_HEAD

Optionally keep the working tree tiny with sparse checkout

If you only need a folder use sparse checkout to avoid downloading the whole tree

git sparse-checkout init --cone
git sparse-checkout set path/to/folder

Run these before checking out if you want the sparse rules applied as the files are written

What to do if the server refuses a raw commit fetch

Some hosting setups block fetching by raw commit id That is annoying but not fatal Fetch a nearby branch or tag then extract the change

  • Fetch a branch that contains or is near the commit
  • Use git cherry-pick COMMIT_SHA to import the change into your branch
  • Or create a patch with git format-patch -1 COMMIT_SHA and apply it locally

Recap and quick tips

  • Find the full commit SHA on GitHub or GitLab
  • Init a fresh repo and add the remote
  • Fetch with depth 1 to avoid pulling full history
  • Create a branch from FETCH_HEAD to avoid a detached HEAD state
  • Use sparse checkout to limit files if you only need a subfolder
  • If direct fetch fails fetch a branch and cherry pick or use format patch

Final tip

Use the full SHA not a short prefix and make a branch off FETCH_HEAD before doing work That way you get the one commit you wanted and you do not trip over detached HEAD problems Later you can merge or rebase like a civilized developer

I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!

This is a dedicated watch page for a single video.