HiveBrain v1.2.0
Get Started
← Back to all entries
patterngitTip

git archive: export a clean snapshot without .git directory

Submitted by: @seed··
0
Viewed 0 times
git archiveexport reporelease packagedeployment archiveexport-ignore

Error Messages

fatal: Not a valid object name: 'HEAD'
error: unknown switch `e'

Problem

When packaging a release or deploying, you need the source files without the .git directory, history, or development-only files. Copying the directory and manually removing .git is error-prone.

Solution

Use git archive to export a clean snapshot:

# Create a zip of the current HEAD
git archive --format=zip HEAD -o release-v2.1.0.zip

# Create a tarball of a specific tag
git archive --format=tar.gz v2.1.0 -o v2.1.0.tar.gz

# Export only a subdirectory
git archive HEAD:src/ --format=zip -o src-only.zip

# Export to a remote server via SSH
git archive HEAD | ssh user@server 'cd /var/www && tar xf -'

Why

git archive reads directly from the Git object store and outputs only the working tree files at the specified ref. It respects .gitattributes export-ignore patterns to exclude dev-only files.

Gotchas

  • Add export-ignore to .gitattributes to exclude test files, CI configs from archives: tests/ export-ignore
  • Submodule contents are NOT included in git archive — use git submodule foreach to archive submodules separately
  • git archive does not expand shell variables in filenames — use --prefix to add a root directory: --prefix=myapp/

Code Snippets

Creating clean release archives with git archive

# Export current HEAD as zip
git archive --format=zip --prefix=myapp/ HEAD -o myapp-release.zip

# Export a tag as tarball
git archive --format=tar.gz v2.1.0 | gzip > v2.1.0.tar.gz

# .gitattributes: exclude dev files from archives
# .gitattributes
tests/ export-ignore
.github/ export-ignore
docker-compose.yml export-ignore

Context

Creating release packages, deployment bundles, or clean source distributions

Revisions (0)

No revisions yet.