Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

I want to copy the last commit from one branch (ie branch-one) to the staging area of another branch (ie branch-two). Is this possible and if so how is it done?

like image 993
Gil Birman Avatar asked Jan 21 '26 10:01

Gil Birman


2 Answers

Checkout the destination branch and clear your staging area. Then use

git cherry-pick --no-commit <commit hash>
like image 168
cowlinator Avatar answered Jan 24 '26 07:01

cowlinator


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.)

like image 30
torek Avatar answered Jan 24 '26 06:01

torek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!