0

I would like to change the branch of my Git repository but not touch the working directory. Essentially change the state of the git repository without changing the state of the working directory. No local files should be overwritten. The difference between the working directory and the state of the branch should become immediately apparent when running git status.

I know that I could just copy out the files, change the branch, and copy them back in. I'm looking for a cleaner solution.

Example:

git init

echo Hello > myfile
git add myfile
git commit -m initial

git checkout -b foo
echo "Good Bye" > myfile
git commit -a -m "first commit on branch foo"

echo "Now I'd like to have this file, unstaged, on branch master after I've already changed it" > myfile
git checkout master # error
Philippe
  • 1,715
  • 4
  • 25
  • 49
  • This is exactly what a `reset` does. It comes in three variations: one that only changes the the branch/commit, one that *additionally* resets the index/staging area to that commit and one *additionally* resets your working directory to that state. The last being a hard reset. – phant0m Jun 17 '20 at 14:34
  • @phant0m OP wants to change the current branch. As much as I know,`git reset` will change current commit but not current branch – Neo Jun 17 '20 at 14:35
  • @Neo Yeah, you're right. – phant0m Jun 17 '20 at 14:36

1 Answers1

0

Stash, (get on the branch if you're not on it now), make the changes and add and commit them, (return to the previous branch if you changed branches), unstash.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • What if there are conflicts between the stashed patch and the other branch? – Philippe Jun 17 '20 at 14:28
  • You aren't going to unstash on the other branch if that isn't where you stashed. And if you do and there are conflicts, resolve them. Conflicts are not bad, they are just a thing like any other thing. – matt Jun 17 '20 at 14:28