Wazery
Wazery

Reputation: 15863

Git stash then checkout each time

Every time I checkout to a different branch on my local Git repo, I need to do the following:

1. git stash
2. git checkout branch_name
3. git stash pop stash@{0}

So I can get my working and staging directories with the checked out branch.

Is there a better and shorter way to do so? Whether its a trick/workaround or a direct built in command?

My way to make it easier is through ZSH alias as following:

myfunction() {
    git stash
    git checkout $1
    git stash pop stash@{0}
}
alias gcost=myfunction

Upvotes: 3

Views: 2611

Answers (2)

Wolf
Wolf

Reputation: 4452

The shorter way to do this is just to checkout the other branch with no stashing. Changes stay in your working copy as long as there are no conflicts (in which case the checkout is refused, and you can use the stash/un-stash method). In other words: uncommitted changes follow you around from branch to branch automatically.

Upvotes: 3

KostaZ
KostaZ

Reputation: 788

I suggest the below flow which I call Work-In-Progress (WIP).

On bug fix branch

git checkout bug_fix_branch
edit some code
git add -u
git commit -m 'WIP: Fix: Bug in network driver e1000'

On feature branch

git checkout feature_branch
git cherry-pick commit-id-of-the-above-commit
edit some code
git add -u
git commit --amend # update the last "WIP" commit with the changes

When the bug fix or the feature are ready to be pushed, just use git commit --amend to remove the "WIP" prefix and then push.

Upvotes: -2

Related Questions