Introduction
When working with Git, you might need to export your repository’s files without the .git directory—whether for deployment, sharing code, or creating backups. The git archive command is a powerful tool that lets you generate a compressed snapshot of your repository without including version control metadata.
In this guide, we’ll explore how to use git archive, its common use cases, and some tips and tricks to make the most of it.
How to Use git archive
The basic syntax of git archive is:
git archive --format=<format> --output=<filename> <branch/commit>
Examples
- Export the latest commit as a ZIP file:
git archive --format=zip --output=repo-export.zip HEAD
- Export a specific branch as a tar.gz file:
git archive --format=tar.gz --output=main-branch.tar.gz main
- Export a specific commit or tag:
git archive --format=zip --output=v1.0.0.zip v1.0.0
- Export only a subdirectory:
git archive --format=zip --output=src-files.zip HEAD:src/
Common Use Cases
1. Deploying Code
Instead of cloning the entire repo on a server, you can export only the necessary files:
git archive --format=tar.gz --output=deploy.tar.gz main | ssh user@server "tar -xzf - -C /var/www/html"
2. Sharing Code Without Git History
Need to send a clean copy of your project? git archive ensures no .git folder is included.
3. Creating Releases
Automate release package generation:
git archive --format=zip --output=release-v2.0.0.zip v2.0.0
4. Backing Up Specific Versions
Export a snapshot of a particular commit for archival:
git archive --format=tar.gz --output=backup-2023-10-01.tar.gz abc1234
Tips and Tricks
1. List Available Formats
Check supported archive formats with:
git archive --list
(Common formats: zip, tar, tar.gz)
2. Include Untracked Files
git archive only exports tracked files. To include untracked files, use git stash or manually add them.
3. Combine with git diff for Partial Exports
Export only changed files between two commits:
git diff --name-only commit1 commit2 | xargs git archive -o changes.zip HEAD
4. Automate with Git Hooks
Use a post-commit hook to auto-export on new commits:
#!/bin/sh
git archive --format=zip --output=latest-commit.zip HEAD
Conclusion
The git archive command is an efficient way to export repository files without the .git directory, making it ideal for deployments, sharing code, and backups. By mastering its options, you can streamline workflows and ensure clean, version-controlled exports.
Next time you need a snapshot of your repo, skip the manual copying and let git archive do the work!
Further Reading:
Up Next in the Series: git bundle – Package a repo into a single file for sharing
Daily advance GIT tips in your inbox---worth starting? Respond to my poll here🚀
For more useful and innovative tips and tricks, Let's connect on Medium
Top comments (0)