Why Is Git Stash Dangerous?
Have you ever stashed your changes on your current feature branch, switched to the main branch to make a hotfix, and then went back to the feature branch? If so, you might have been in danger of unintentionally leaking some of the new feature files into the main branch.
Consider the following scenario: On your feature branch, you created a new file
new-cool-feature.js. Suddenly, an urgent fix was requested, so you did
git stash. You checked out the master branch, created a file
git add --all && git commit -m ‘Fix’, and pushed the branch. Unexpectedly,
new-cool-feature.js would end up being pushed to your master branch. This is because
git stash works just like
git commit -a, meaning it ignores new files that are not yet tracked by Git.
This has two advantages:
- No need to memorize additional stashing commands, like list all stashes, or stash untracked files. It is the usual Git commit routine with
git commit, and
- In case you have WIP commits on several branches, there is no need to pick the needed one when you are back, as in the case of a stash. It is always the same
git reset HEAD^.
However, I’d say there is one case when
git stash is safe and convenient to use, which is when you want to see how your uncommitted code changes the behavior of the software. In this case, you can quickly do
git stash, see how it worked before your new changes, and then
git stash pop to go back. Not stashing some files accidentally, in this case, has virtually no consequences, as you will unstash on the same branch in a moment anyway. There is also no issue of picking the right stash from a list.
How to Create Very Short Shortcuts?
Adding aliases to
.gitconfig has the advantage of retaining Git autocomplete, but it also has a disadvantage. These commands are still at least five characters long, like
git c, and five characters is still too long for a command that you type dozens of times throughout your day. If you take an alternative path and create a bash alias like
gc, you will lose autocomplete. Luckily, there is a way to make autocomplete work with Bash aliases. Bash uses a command
__git_complete that you can use to register your aliases. Add the following to one of your RC scripts:
alias gc=’git checkout’ . /usr/share/bash-completion/completions/git __git_complete gc _git_checkout
The second line eagerly loads Git autocompletion functions into Bash, without it, they are loaded only after you try to autocomplete your first Git command. To see a list of Git commands that
__git_complete accepts, type
_git_ and trigger autocompletion. This is confirmed to work with Git 2.7.4 and Bash 4.3.12.