How can I push specific commit to a remote, without the previous commits?

I committed code in local repository 2 or more times using

git commit -m "message 1"
git commit -m "message 2"
git commit -m "message 3"

Now I have three commits with following SHA

commit-1 SHA1
commit-2 SHA2
commit-3 SHA3

But I want to push only commit-2 in remote repository using git push.
If I run git push then it will push all commits.
And I also tried following commands:

git push SHA2

but this also pushed all commits.

How to push this only commit-2 in remote repository ?


You need to git rebase -i your branch first, in order to make commit2 the first commit after origin/yourBranch .

 x--x--C1--C2--C3 (B)
    |
  (origin/B)

git rebase -i C1~

 x--x--C2'--C1'--C3' (B)
    |
  (origin/B)

Then you can push that commit.

See "git - pushing specific commit":

git push <remotename> <commit SHA>:<remotebranchname>
# Example
git push origin 712acff81033eddc90bb2b45e1e4cd031fefc50f:master

It does push all commits up to and including the commit you choose.
But since your commit is the first one, it only pushes that commit.


I would not recommend cherry-picking, as it changes the SHA1 of the commits pushed: when you will eventually push your full branch, you will end up with duplicate commits.


You can also use cherry-pick to do it but your local branch with the unpushed commits will divert from your remote branch.

在这里输入图像描述


How to do it?

# cd into your project folder

# create new branch based on the origin branch (latest code in remote)
git checkout -b <new branch> origin/master

# "grab" the commit you wish to use
git cherry-pick <SHA-1>

# now your branch contains the desired commit.
# push it back to your remote.

############################################################################
### Note: you might not be able to push if you try to push it back to    ### 
###       master. To fix it you might need to rename the original master ###
###       and your then rename the new barch to master                   ###
############################################################################
链接地址: http://www.djcxy.com/p/49806.html

上一篇: 只推送最后一次提交与TortoiseGit

下一篇: 我如何将特定提交推送到远程,而无需提交以前的提交?