Git - exclude specific commit and push

Use (replace the 1 with the number of commits you want to ignore from the top):

git push origin HEAD~1:$(git rev-parse --abbrev-ref HEAD)

Note: for this command to work the remote branch needs to exist, or you'd get an error: unable to push to unqualified destination. If you're getting the error, you may for example start with pushing the branch as usual (i.e. including the commits you didn't want to push), and then repeat the command above with the additional argument --force.

Other alternatives (old answer)

Just wanted to note an alternative, because creating a separate branch, then doing some magic, then deleting it, sounds like too much hassle; especially so if you already has a pull request opened, and you need to push exactly the branch you're currently on.

A simpler way is (but please, don't intersperse it with other git commands, or you may need to dig in reflog for the point to restore):

$ git reset --hard HEAD~1   # temporarily erase commits, use in place of "1" the number of commits you want to ignore
$ git push myorigin HEAD    # do the push wherever you wanted
$ git reset --hard HEAD@{1} # restore commits

The trick used here is that git usually locally stores destructive operations you did in place called reflog. You can see its content with git reflog command (or the usually more readable git reflog --date=iso, though you won't see the easier to write marks HEAD@{n} in this case).


If you don't feel confident, a safer version might be:

$ git format-patch -1 --stdout > 1.patch # store commits in a file, use in place of "1" the number of commits you want to ignore
$ git reset --hard HEAD~1 # temporarily erase commits, use in place of "1" the number of commits you want to ignore
$ git push myorigin HEAD  # do the push wherever you wanted
$ git am 1.patch          # restore commits

You will need to have a new branch with the desired commits.

You can do it in several ways


git cherry-pick

Checkout a new branch to the specific sha-1 you want to start from:

git checkout <origin branch>
git checkout -b <new branch>

# now cherry-pick the desired commits onto the new branch
git cherry-pick commit1 commit2 ... commitN

# now push to remote
git push origin remote <branch name>

Other options:

git revert

git revert SHA-1

Use git revert to undo the changes you have made in the unwanted commit, the result will be branch with the old code and the new code but the current state will be the original code


git rebase -i

Interactive rebase. choose the commit you don't want and remove it.

# X is the number of commits you wish to squash
git rebase -i HEAD~X

Once you squash your commits - choose the e for edit and place the code you want it to be, add and commit

enter image description here


git filter-branch

Filter branch can be used to filter any content you want.

git filter-branch --env-filter '<do what ever you want on this commit range' SHA1..SHA1