Skip to content

Instantly share code, notes, and snippets.

@mesheets
Last active July 9, 2024 01:21
Show Gist options
  • Select an option

  • Save mesheets/bf31d8abc2c70537efc01739e8367dc8 to your computer and use it in GitHub Desktop.

Select an option

Save mesheets/bf31d8abc2c70537efc01739e8367dc8 to your computer and use it in GitHub Desktop.
Purge Git History (for Repositories without Submodules)
#!/bin/sh
# Purge Git history (for repositories without submodules)
# Useful for reducing the size of a repository when history is no longer needed
# Helpful also when needing to remove file(s) from Git history
# SUSE Bash - https://documentation.suse.com/sles/12-SP4/html/SLES-all/cha-adm-shell.html
# - General shell scripting - https://www.shellscript.sh/
# ** IMPORTANT NOTE: NOT FOR REPOSITORIES WITH SUBMODULES ** #
# Based in part on the following:
# - https://gist.github.com/stephenhardy/5470814?permalink_comment_id=2225724#gistcomment-2225724
# - https://stackoverflow.com/a/71878364
# - https://stackoverflow.com/q/9683279
# ~ The "git gc --aggressive --prune=all" options did not seem to work. Try with "git push --mirror"?
# ~ https://stackoverflow.com/q/2116778
if [ ! -e .git/config ] ; then
echo "Command must be executed from the root of a Git repository"
exit
fi
# Backup the Git folder to a temp location
GIT_TEMP_DIR=`mktemp -d git-purge-temp_XXXXXXX --tmpdir`
mv .git "$GIT_TEMP_DIR/.git"
# Reinitialize git repository
git init
# Restore the Git configuration file
cp --preserve=all "$GIT_TEMP_DIR/.git/config" ".git/config"
# Commit the current contents
git add .
git commit -m "Reset commit"
# Force-push a mirror of the reset repository
git push --mirror --force
# Cleanup backup files and folders
rm -rf "$GIT_TEMP_DIR"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment