Gil Birman Gil Birman -4 years ago 140
Git Question

How do you copy a specific git commit to the staging area?

I want to copy the last commit from one branch (ie

) to the staging area of another branch (ie
). Is this possible and if so how is it done?

Answer Source

The git checkout command writes through the index/staging-area to the work directory, so checking out files does the job (though it updates the work directory whether you want that or not).

The problem, of course, is that git checkout commit switches branches, or detaches HEAD. The trick to avoid this is to check out specific files, which avoids this branch-switching:

git checkout branch-one -- path/to/file.ext

If you check out the entire tree, you'll get all the files. Assuming you're in the top level directory:

git checkout branch-one -- .

will do the trick.

One other caveat: this will not remove from the staging area any file that does not exist in branch-one. If you want that as well, start by removing everything (the staging area will get repopulated by checking out all the files in the other branch):

git rm -rf .
git checkout branch-one -- .

(adjust as needed if you don't want to copy the other branch's .gitignore, etc; note that you can restore specific files from branch-two, aka HEAD, with:

git checkout HEAD -- path

if desired).

(As usual, be sure the state of the work directory is clean before doing this.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download