Change files in working directory while not changing branch

60 Views Asked by At

In order to create a clean commit history and get rid of some files I don't want for a PR, I would like to set my working directory to be at the state of my branch, say B, but make git remain on branch A which is identical with main, so I can now stage whatever I want to be part of the commit.

In other words: I want to be on main, but have the working directory be like the working directory of another branch A.

I know I can git rebase and edit, but that involves a lot of steps. I simply want to change the files in the working directory and nothing else.

I've found a hacky way but is there something simpler than:

git branch -c A B
git reset --soft main
git restore --staged .
1

There are 1 best solutions below

0
Cornelius Roemer On

Using git checkout COMMIT . instead of git reseset appears to be slightly more intuitive to me:

git branch -c A main
git checkout B .
git restore --staged .

(from https://stackoverflow.com/a/49572040/7483211)

But using git reset --mixed is actually the most succinct I think:

git branch -c A B
git reset --mixed main

as --soft puts changes in staging, while --mixed makes changes unstaged.