Search code examples
gitgithubgit-branchgit-stash

Git - stash to branch - files in stash being re-applied to master


I'm new to git I've watched hours of videos and whilst it seems logical I'm failing dismally and always end up in trouble.

I'm trying to stash my current uncommitted and untracked changes and 'unstash' them into a branch as per the manual. I do this:

git add .
git stash
git stash branch my_new_branch

It switches to the branch and the unstashed files are there - but they have also been unstashed in the master branch. Is this correct?

Prior to the unstash the master branch is clean if I do a git status

EDIT: Thanks @VonC... This is what I was trying to achieve and I've realised now I just didn't go far enough with it

I create an empty repo and added file1 and file2 and committed them.

Then I added file3 and file4 and stashed them, then unstashed them to branch3and4

They were then visible in both master and branch3and4

I checked out branch3and4 and committed the files

Then when I went back to master the files were gone - which is exactly what I wanted, so now I can toggle between the two branches and see a different set of files when I 'ls'


Solution

  • but they have also been unstashed in the master branch. Is this correct?

    Not exactly: as long as those files aren't common with the ones versioned in master branch, switching back to master would still keep those untracked files.

    File added to the index shouldn't be in master anymore (and you should commit them to my_new_branch first before git checkout master, or those modifications would be lost (or at least harder to recover)