Sometimes you have made some changes into your local copy and you don’t want to make a commit because your code doesn’t compile, but something came up and you should change your branch for instance and you will lose your local changes. In this situation, you can stash your changes and save your changes and change your branch for instance. The command saves your local modifications away and reverts the working directory to match the HEAD
commit.
Let’s have a complete example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
mkdir repos1 mkdir repos2 mkdir remote_repose cd repos1 git init git init --bare ../remote_repose/ git remote add origin ../remote_repose/ touch A.txt git add -A git commit -a -m 'A.txt added' git push --set-upstream origin master touch B.txt git add -A git commit -a -m 'B.txt added' git push --set-upstream origin master |
now we make some change:
1 2 |
date > A.txt ls > B.txt |
now let’s stash changes:
1 |
git stash |
stash@{0}
is the most recently created stash, stash@{1}
is the one before it. WIP stands for work in progress. We can list and drop changes by:
1 2 3 4 5 6 7 8 |
git stash list git stash drop git stash save <msg> git stash list git stash show -p <stashid> git stash drop <stashid> git stash drop git stash pop |
We can use gitk to see the changes and :
1 |
gitk --all |
Now let’s create a branch and one more stash and apply the previous stash from the master branch there:
1 2 3 4 |
git checkout -b feature-b ls > new git add . git stash apply stash@{1} |
To see all stash in gitk
1 |
gitk `git stash list --format=%H` |
To checkout a specific file from stash:
1 |
git checkout stash@{0} <filepath> |
To view the file in the stash:
1 |
git stash show |
stash@{0}^1
means the first parent of the given stash, which as stated in the explanation above is the commit at which changes were stashed away.
1 |
git diff stash@{0}^1 stash@{0} -- <filename> |