gitversion-controlgit-branch-sculpting

How does one move a file erroneously added to a branch / commit to a different branch / commit in Git?


enter image description here

I have a file (driver_06_05_2015.view) in branch ServiceProvisionSpecialist_06_08_2015 that shouldn't be there and was mistakenly committed to that branch even though it should be in the driver_06_05_2015 branch.

Is there a way I can move just the file (not the entire commit) to the driver_06_05_2015 branch by rewriting history (I think when people say that it refers to the rebase command...)


Solution

  • Update: using rebase now as I saw you need to edit the second to last commit.

    You can use interactive rebase, and rebase onto the parent commit of the one you'd like to edit. In this case,

    git rebase -i HEAD~2
    

    In the editor, replace pick with edit on the line of the commit that has added the file you'd like to delete. Then close the editor.

    The interactive rebase will stop at that commit, now you can edit:

    git rm --cached socialMediaGenerator/src/driver_06_05_2015.view
    git commit --amend
    git rebase --continue
    

    The --cached option allows you to remove a file from Git but keep it on your disk. Then you can add it in another branch:

    git checkout driver_06_05_2015
    git add socialMediaGenerator/src/driver_06_05_2015.view
    git commit -m "Add file driver_06_05_2015.view"