Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How keep uncommited and untracked files in just specific branch?

Tags:

git

My problem is:

I was working in a new functionality on branch master, because I forgot to create the branch.

Now, I create the branch e use:

git stash
git checkout new_branch;
git stash apply

But, the uncommit and untrack files, when I back to master branch, stay in master.

Why?

The correct is add files and commit in new branch, or I can keep this uncommited/untracked?

like image 763
Patrick Maciel Avatar asked Feb 03 '26 17:02

Patrick Maciel


2 Answers

Uncommitted/untracked files are not in any branch. They are untracked. What you are seeing is that git tries hard not to destroy anything in your working directory that it cannot recover. So, when you switch branches, it does nothing at all to untracked files - it just leaves them there. They will still show up as untracked in the new branch, just like they did in the old branch.

The caveat to that is when you switch from a branch where a particular file was untracked, to a branch where that file is tracked, and the version of the file in your working directory does not match the one that would be checked out. In that case, git will yell at you and refuse to check out the new branch, because checking out that file would lose your data. You can override this with git checkout -f if you really want to. A similar situation occurs if you switch from a branch where a file is tracked, but you've made changes you haven't committed yet, and the new branch doesn't track that file.

like image 86
twalberg Avatar answered Feb 06 '26 07:02

twalberg


The original poster says:

The correct is add files and commit in new branch, or I can keep this uncommited/untracked?

The short answer is, yes, you have to add and commit untracked files to a branch to isolate them to that branch:

git add <file>
git commit