Question :
Imagine that I have in the master branch a commit of a texte.txt
file. So I create a branch called teste2
, I checkout it and create a file called teste2.txt
, but I do not commit it.
If I give git checkout master
and check git status
, it considers the changes (in this case the creation of teste2.txt
) as belonging to the master branch, even though I made those changes when it was in the teste2
branch %.
Is there a way to keep these changes in branch teste2
without having to commit? Because I may not want to commit, if I have not yet completed what I’m implementing.
Answer :
It is only possible to have pending changes in the branch that is currently being used.
When you have pending changes, and if you want to change branches, it is customary to save the changes in a stash .
For example, using the use case in question, if we are in branch teste2
, we can save the changes in a stash like this:
git stash //stash anonima
git stash save "adicionado teste2.txt" //stash com nome
Now, we can switch to the master
branch and work on other files.
git checkout master
When we return to the teste2
branch, just apply the stash again to restore the initial state:
git checkout teste2
git stash list //ver lista das stashes
git stash apply //aplica a ultima stash que foi gravada
git stash apply stash@{0} //aplica a stash no index 0
git stash apply stash^{/adicionado} //aplica uma stash especifica (pesquisa por regex)
Note: When apply , the stash is still stored in the stack. If we want to apply and to delete the stash, we use git stash pop
. We can also use git stash list
to list all stashes currently in the stack.