Skip to content

Instantly share code, notes, and snippets.

@zetekla
Last active July 10, 2017 00:34
Show Gist options
  • Save zetekla/23edf79f451e2dddc7b21c347888d3a7 to your computer and use it in GitHub Desktop.
Save zetekla/23edf79f451e2dddc7b21c347888d3a7 to your computer and use it in GitHub Desktop.
Git rebase and delete some commits
#!/bin/bash
if [ $# -ne 1 ]; then
echo "Missing parameter: number of commits to squash."
exit 1
fi
echo "Squashing $1 commits..."
git reset --soft HEAD~$1
git log --format=%B%n --reverse "HEAD@{1}" -n $1 > _msg.txt
git commit -t _msg.txt
rm _msg.txt
echo "Done!"
# src: https://stackoverflow.com/questions/5189560/squash-my-last-x-commits-together-using-git
# rebase to a SHA
git rebase -i ffaf479
# fix conflict (Resolve Conflict..) in IntelliJ
# register changes
git add .
# continue rebase until no conflict, if conflict, resolve and `git add .` again
git rebase --continue
# change <pick> to <squash> or comment out # the SHA
once finished, perform `git add -A` or `git checkout -b <new branch>` to create a new branch and push to it.
@zetekla
Copy link
Author

zetekla commented Jul 9, 2017

Removing the last commit

To remove the last commit from git, you can simply run git reset --hard HEAD^ If you are removing multiple commits from the top, you can run git reset --hard HEAD~2 to remove the last two commits. You can increase the number to remove even more commits.

If you want to "uncommit" the commits, but keep the changes around for reworking, remove the "--hard": git reset HEAD^ which will evict the commits from the branch and from the index, but leave the working tree around.

If you want to save the commits on a new branch name, then run git branch newbranchname before doing the git reset.

Src: https://sethrobertson.github.io/GitFixUm/fixup.html

@zetekla
Copy link
Author

zetekla commented Jul 10, 2017

To squash four commits into one, do the following:

$ git rebase -i HEAD~4
In the text editor that comes up, replace the words "pick" with "squash" next to the commits you want to squash into the commit before it. Save and close the editor, and git will combine the "squash"'ed commits with the one before it. Git will then give you the opportunity to change your commit message to something like, "Issue #100: Fixed retweet bug."

Important: If you've already pushed commits to GitHub, and then squash them locally, you will have to force the push to your branch.

$ git push origin branch-name --force
Helpful hint: You can always edit your last commit message, before pushing, by using:

$ git commit --amend

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