Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (29.3k points)

Sometimes it happens that I make some changes in my working directory and I realize that these changes should be committed in a branch different to the current one. This usually happens when I want to try out new things or do some testing and I forget to create a new branch beforehand, but I don't want to commit dirty code to the master branch.

So, how can I make that uncommitted changes (or changes stored in the index) be committed to a different branch than the current one?

1 Answer

0 votes
by (50.2k points)

Since your files are not committed in the branch so you can use the following commands:

git stash

git checkout branch2

git stash pop

Or you can use 

git stash

git checkout branch2

git stash list       # to check the various stash made in a different branch

git stash apply x    # to select the right one

And to stash currently untracked (newly added) files:

git stash -u

reference:https://git-scm.com/docs/git-stash#_options

Alternatively, if you realize that this is going to happen in the future, simply commit the things that belong to the current branch. You can always come back and amend that commit:

git add -p

git commit

git stash

git checkout other-branch

git stash pop

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...