Skip to content

Instantly share code, notes, and snippets.

@Zibri
Last active July 17, 2025 00:30
Show Gist options
  • Save Zibri/76614988478a076bbe105545a16ee743 to your computer and use it in GitHub Desktop.
Save Zibri/76614988478a076bbe105545a16ee743 to your computer and use it in GitHub Desktop.
Bash script to remove all revisions from github or gist repository.
#!/bin/bash
#
# By Zibri (2019)
#
# Usage: gitclean username password giturl
#
gitclean ()
{
odir=$PWD;
if [ "$#" -ne 3 ]; then
echo "Usage: gitclean username password giturl";
return 1;
fi;
temp=$(mktemp -d 2>/dev/null /dev/shm/git.XXX || mktemp -d 2>/dev/null /tmp/git.XXX);
cd "$temp";
url=$(echo "$3" |sed -e "s/[^/]*\/\/\([^@]*@\)\?\.*/\1/");
git clone "https://$1:$2@$url" && {
cd *;
for BR in "$(git branch|tr " " "\n"|grep -v '*')";
do
echo working on branch $BR;
git checkout $BR;
git checkout --orphan $(basename "$temp"|tr -d .);
git add -A;
git commit -m "Initial Commit" && {
git branch -D $BR;
git branch -m $BR;
git push -f origin $BR;
git gc --aggressive --prune=all
};
done
};
cd $odir;
rm -rf "$temp"
}
@pa-0
Copy link

pa-0 commented Dec 8, 2024

For the command substitution at line 19, does it make more sense to remove the double quotes?

@0wwafa
Copy link

0wwafa commented Jul 17, 2025

#!/bin/bash

# Get a list of all local branches
# The 'sed' command removes the '*' from the current branch
for branch in $(git branch | sed 's/\*//' | awk '{print $1}'); do
  echo "--- Working on branch: $branch ---"

  # Switch to the branch you want to reset
  git checkout "$branch"

  # Create a new, temporary orphan branch. This branch has no history.
  git checkout --orphan temp-reset-branch

  # Stage all the files from the original branch
  echo "Staging all files..."
  git add -A

  # Create the new initial commit
  echo "Creating the new initial commit..."
  git commit -m "Initial Commit"

  # Delete the old local branch
  echo "Deleting the old local branch: $branch"
  git branch -D "$branch"

  # Rename the temporary branch to the original branch's name
  echo "Renaming temp-reset-branch to $branch"
  git branch -m "$branch"

  # Force-push the new branch to the remote repository
  echo "Force-pushing $branch to origin..."
  git push -f origin "$branch"

  echo "--- Finished processing branch: $branch ---"
  echo ""
done

# Run garbage collection once at the end to clean up old objects
echo "--- Running garbage collection to finalize the reset ---"
git gc --aggressive --prune=all
echo "--- Repository reset complete ---"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment