Search code examples
gitgit-branchgit-rebase

git rebase doesn't contain every files


by mistake I used "git rm my_file" in my branch.

After some commits, merges and... now I'm trying to get the file back from master branch, I'm using "git rebase master" and it says current branch is up to date but the file doesn't exist.

Is there anyway to get the file from master to my branch? I think simply creating a new branch will fix the problem.


Solution

  • Since you tell the file is still there on master, you can simply get the file from master and commit it:

    git checkout master -- path-and-name-of-the-deleted-file
    git commit
    

    Note the dashes with spaces around them " -- " to let git treat the part right of them as file name even if the file is deleted.

    This is the simplest way, but in your commit history, this file will be deleted and recreated, what is not very pretty.

    If you want to have a clean history, you can try to undo the deletion:

    Find the commit id where you deleted the file:

    git log --name-status --diff-filter=D
    

    Let's say it's commit abcdef123456. Then do a interactive rebase to the parent of that commit:

    git rebase -i abcdef123456^
    

    (the caret ^ means parent commit)

    You'll get a playbook of all your commits you made since deleting the file. The topmost will be abcdef123456, looking like

    pick abcdef12
    

    Change from "pick" to "edit", save, exit the editor. git will start the rebase and will stop after the first commit.

    Then get the current version of the file from master:

    git checkout master -- path-and-name-of-the-deleted-file
    git commit --amend
    git rebase --continue
    

    ... and your deleting will be undone.