Git Clone Explained — Clone Specific Branches and Shallow Clones
When we run git clone, by default it copies the entire repository along with all its branches and commit history.
But what if:
- You only want one specific branch?
- You don’t need all commits and just want the latest few?
That’s where --branch, --single-branch, and --depth options come into play.
Let’s explore these step by step. 🚀
Cloning All Branches (Default Behavior)
When you run a normal git clone, Git downloads all remote branches as tracking branches.
git clone <repo-url>
cd <repo-name>
git branch -a
👉 Output:
* main
remotes/origin/main
remotes/origin/test
remotes/origin/dev
✅ By default, you get all branches.
Clone Only a Specific Branch
Suppose you want to clone only the test branch, without downloading the rest.
You can use:
git clone --single-branch --branch test <repo-url>
Now check the branches:
cd <repo-name>
git branch -a
👉 Output:
* test
remotes/origin/test
✅ Only the test branch is cloned, no extra branches.
Shallow Clone (Limit Commit History)
By default, Git clones the entire commit history of the branch. But sometimes you just want the last commit or a few recent ones.
Use the --depth option:
git clone --single-branch --branch test --depth 2 <repo-url>
👉 This clones only the last 2 commits of the test branch.
Check the logs:
git log --oneline
👉 Output:
a1b2c3d Last commit message
f9e8d7c Second last commit message
✅ Only 2 commits are present instead of the full history.
Summary
git clone <url>→ Clones entire repo with all branches and commits.git clone --single-branch --branch <branch> <url>→ Clones only the specified branch.git clone --depth <n>→ Creates a shallow clone with only last n commits.- Useful for saving time and space when you don’t need full history.
Keep Learning 🚀
👉 Subscribe to Learning Ocean – Subscribers get coupon codes for my courses, early access to blogs and courses, and even exclusive YouTube videos.
👉 My YouTube Channel – More videos, more fun, and lots of learning!
👉 📺 Watch this topic in video form
Stay curious, keep coding, and let’s make learning fun together! 🎉