git-clone@ubuntu:~$ 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:
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.
git-clone@ubuntu:~$ 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.