How to perform a shallow git clone
[email protected]:~$ git clone --depth 5 https://github.com/cameronmcnz/my-github-repo.git
That’s how you perform a shallow git clone. You specify a depth as an option in the clone command, and when the shallow git clone command completes, your local repo will only contain a history of that many commits.
Shallow git clone benefits
Why would any developer or DevOps professional want to perform a shallow git clone? To limit the size of the repository that gets downloaded to the local machine is a big one. Other shallow git clone benefits include:
- A shallow git clone makes it easier to search the recent Git history and troubleshoot problems
- Only the Git branch of interest is cloned
- A long history of unneeded commits is not downloaded
- The disk space used by a shallow git clone is minimal
- A shallow git clone runs faster than a normal git clone
Shallow git clone steps
The list of steps to perform a shallow git clone are:
- Obtain the http url of the repository to clone
- Include the –depth 5 option in the git clone command
- Run the git clone command in the BASH shell
- Switch into the directory created by the shallow git clone
- Perform a git log –oneline operation to verify the clone depth
Shallow git clone surprise
One surprise developers get when performing a shallow git clone operation is the fact that only a specific branch is pulled back to the local repository. Implicit in the shallow clone is the –single-branch switch, meaning no other branches will be available locally. Any attempt to switch to a branch that is otherwise available on the remote repository will trigger a pathspec error.
Shallow clone a specific branch
By default a shallow git clone will operate on the master branch. However, if you would prefer to git clone a specific branch, all you need to do is specify that branch name of interest with the –branch switch.
[email protected]:~$ git clone --depth 5 https://github.com/cameronmcnz/my-github-repo.git my-directory
Shallow clone to a directory
Note that in the shallow git clone command issued above, the directory to clone into was also specified by adding test my-directory at the end of the operation. The ability to specify a directory name is helpful when writing continuous integration routines that must clone multiple branches of the same repository and each clone operation requires a unique folder.
In the end, it is nice to keep your build folders lean so there’s not future need to clean up Git repositories that contained branches and commits that nobody ever used.