git: push a single commit

You may be looking for:

git push origin $commit:$branch

Credit: http://blog.dennisrobinson.name/push-only-one-commit-with-git/

Explanatory notes:

  • Pushing a commit pushes all commits before it (as Amber said). The
    key is to reorder your commits first (git rebase -i), so they are
    in the order you want to push them.
  • $commit doesn’t have to be a sha1. For example,
    “HEAD~N” would push everything before the last N commits.
  • $branch (typically “master” or “main”) is the branch you push to – the remote branch. It does not have to be the same as a local branch.
  • If you need to get some commits out of the way locally, you can use the cherry-pick method (suggested by midtiby) to move them onto a separate local branch first. But as shown here, it’s not necessary to create a local branch for the purpose of pushing to a remote branch. You can work on multiple branches at once if you are careful about which commits you push where.

If the remote branch does not exist yet, and you want to create it, it must be prefixed with refs/heads/ (to disambiguate branch from tag):

git push origin $commit:refs/heads/$branch

And as a variation of this theme, deleting a remote branch can be thought of as pushing no commit to it:

git push origin :$branch

Pro tip: git-revise is a tool for massaging your commit stack into shape before pushing. It has a similar interface to git rebase. This tool is irreplaceable (correct me if I’m wrong) for sufficiently hard commit untangling jobs, though its interface is in dire need of replacement.

Leave a Comment