102

Is there a way to push all my local commits to the remote repository except the most recent one? I'd like to keep the last one locally just in case I need to do an amend.

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
python dude
  • 7,980
  • 11
  • 40
  • 53

3 Answers3

127

Try this (assuming you're working with master branch and your remote is called origin):

git push origin HEAD^:master

HEAD^ points to the commit before the last one in the current branch (the last commit can be referred as HEAD) so this command pushes this commit (with all previous commits) to remote origin/master branch.

In case you're interested you can find more information about specifying revisions in this man page.

Update: I doubt that's the case, but anyway, you should be careful with that command if your last commit is merge. With merge commit in the HEAD HEAD^ refers to the first parent of that commit, HEAD^2 - to its second parent, etc.

KL-7
  • 46,000
  • 9
  • 87
  • 74
  • 2
    If you're on Windows, make use you quote the `^` by doubling it up or you'll wind up pushing everything: `git push origin HEAD^^:master` – Ferruccio Dec 28 '20 at 12:02
  • 2
    I got `zsh: no matches found: HEAD^:master`. If you use zsh (or have EXTENDED_GLOB enabled), you need to escape the caret: `\^` – Cody Apr 07 '21 at 18:28
  • Do I need to mention my local branch and remote if I want to push the current branch to the setup remote? Or could I just `git push HEAD^`? – Herr Derb Apr 07 '22 at 09:32
48

A more general approach that works to push up to a certain commit, is to specify the commit hash.

git push <remote> <commit hash>:<branch>

For example, if you have these commits:
111111 <-- first commit
222222
333333
444444
555555
666666 <-- last commit

git push origin 555555:master

..Will push all but your last commit to your remote master branch, and

git push origin 333333:myOtherBranch  

..Will push commits up to and including 333333 to your remote branch myOtherBranch

Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
  • error: The destination you provided is not a full refname (i.e., starting with "refs/"). We tried to guess what you meant by – Kasra Jul 06 '20 at 08:28
15

Another possibility is to

git reset --soft HEAD^

to uncommit your most recent commit and move the changes to staged. Then you can

git push

and it will only push the remaining commits. This way you can see what will be pushed (via git log) before pushing.

Jarett Millard
  • 5,802
  • 4
  • 41
  • 48