I was working on a git branch and was ready to commit my changes, so I made a commit with a useful commit message. I then absentmindedly made minor changes to the code that
Follow these steps:
git stash save
git checkout branch
git stash pop
well, it should be
git stash save
git checkout branch
// do something
git checkout oldbranch
git stash pop
You need a clean state to change branches. The branch checkout will only be allowed if it does not affect the 'dirty files' (as Charles Bailey remarks in the comments).
Otherwise, you should either:
Or, more recently:
git switch -f <branch-name>
-f
is short for --force
, which is an alias for --discard-changes
)Proceed even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
This differs from git switch -m <branch-name>
, which triggers a three-way merge between the current branch, your working tree contents, and the new branch is done: you won't loose your work in progress that way.
I created a .gitconfig
alias for this:
[alias]
spcosp = !"git stash push && git checkout \"$@\" && git stash pop --index #"
To change to new-branch-name
, use:
git spcosp new-branch-name
And any non-commited file and index changes will be kept.
Follow,
$: git checkout -f
$: git checkout next_branch
If you want to keep the changes and change the branch in a single line command
git stash && git checkout <branch_name> && git stash pop