How to Clone with Depth in Git: Shallow Clone Explained
Use
git clone --depth <number> <repository-url> to clone a repository with limited commit history. This creates a shallow clone with only the latest commits up to the specified depth, speeding up cloning and saving disk space.Syntax
The --depth option in git clone limits the number of commits cloned from the repository history.
git clone: Command to copy a repository.--depth <number>: Limits history to the last <number> commits.<repository-url>: URL or path of the repository to clone.
bash
git clone --depth <number> <repository-url>
Example
This example clones the latest 3 commits from a public GitHub repository, creating a shallow clone.
bash
git clone --depth 3 https://github.com/git/git.git
Output
Cloning into 'git'...
remote: Enumerating objects: 1000, done.
remote: Counting objects: 100% (1000/1000), done.
remote: Compressing objects: 100% (500/500), done.
Receiving objects: 100% (1000/1000), 2.5 MiB | 1.2 MiB/s, done.
Resolving deltas: 100% (600/600), done.
Common Pitfalls
Common mistakes when using --depth include:
- Trying to fetch commits beyond the shallow clone depth later without unshallowing.
- Using shallow clones for operations that require full history, like some merges or rebases.
- Not specifying a depth, which clones the full history by default.
To fix shallow clone limitations, you can deepen the clone later with git fetch --deepen <number> or convert to full clone with git fetch --unshallow.
bash
git clone --depth 1 https://github.com/git/git.git # Later, to get full history: git fetch --unshallow
Quick Reference
| Option | Description |
|---|---|
| --depth | Clone only the last |
| --shallow-since | Clone commits newer than the given date |
| --shallow-exclude | Exclude commits reachable from the specified commit |
| --unshallow | Convert shallow clone to full clone by fetching all history |
| --deepen | Increase the depth of the shallow clone by |
Key Takeaways
Use
git clone --depth <number> to create a shallow clone with limited commit history.Shallow clones save time and disk space by downloading fewer commits.
Some Git operations require full history; shallow clones can be deepened or unshallowed later.
Without
--depth, git clone downloads the entire repository history.Use
git fetch --unshallow to convert a shallow clone into a full clone.