kes@work ~/c $ git status
On branch fix_typos_and_do_small_improvements
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: dancer/_global/t/lib/Global/Test/Routes.pm
Untracked files:
(use "git add <file>..." to include in what will be committed)
Utils.pm
kes@work ~/c $ git checkout check_responses_from_backend
error: Your local changes to the following files would be overwritten by checkout:
dancer/_global/t/lib/Global/Test/Routes.pm
Please commit your changes or stash them before you switch branches.
Aborting
I know, I did changes at my working directory and before switching branches I should stash my changes. I did that and that works well, but not now.
Here I create file at my current working directory and I do not want to lose these changes. It is new for current branch, but this file already exists at the branch I want to switch to.
Why I can not switch to different branch? I do not see any problem that that could not be done. Please explain what is happened here. Thank you.
** git version 2.35.3
CodePudding user response:
You can. You just have to use the flag -f
but it will cause the unstaged file to be overwritten by what comes from the destination branch. This is not normally wanted so you have to explicitly say so.
CodePudding user response:
Why I can not switch to different branch?
You have a file that, in your working tree and your current branch, is untracked. (This file is named dancer/_global/t/lib/Global/Test/Routes.pm
.)
That other branch name check_responses_from_backend
selects a commit in which this same file is tracked and committed.1 In order to switch to that branch, Git must overwrite your current version of the file.
Git is telling you exactly this. Git is saying: If I do what you asked, you will lose the contents of your file. PLEASE PLEASE PLEASE SAVE THOSE CONTENTS and if you fail to do that don't blame me!
The easiest way to deal with this is for you to save the contents of that file by making it tracked and committing, or by moving it to some other name, possibly entirely out of your working tree. You can then switch to that other branch, because the file's contents are safely saved away under some other name or in some commit. When you want those contents back later, you get them from that other name, or from the commit you made.
1Technically, it's just "committed": the tracked-ness of the file depends on the action that happens during your git checkout
or git switch
. But if you successfully check out that branch, you'll have a tracked file, which will have the contents from that commit.