Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent 'git checkout' if uncommitted changes

Tags:

git

I frequently have a bad time because I checkout a branch with uncommitted changes that I should have committed before changing branches but forgot. Is there a way using some git config I can have the git checkout fail if there are any pending changes or new files? I've recently gotten into the habit of running git status before git checkout, but that's inconvenient and still prone to forgetfulness. I can probably use a Bash alias to chain those two commands together in some way, but I'm hoping there's either something I can throw in my .gitconfig or a flag that I'm not seeing in git config's man page.

like image 957
smjZPkYjps Avatar asked Sep 20 '13 14:09

smjZPkYjps


People also ask

Does git checkout remove uncommitted changes?

Git stash lets you discard changes and save them for later reuse. Try Git checkout --<file> to discard uncommitted changes to a file. Git reset --hard is for when you want to discard all uncommitted changes.

Can I checkout branch without commit?

you can do git checkout -m <branch-name> to merge conflicts and checkout to the branch and resolve conflicts yourself, or git checkout -f <branch-name> to ignore changes.

What happens to uncommitted changes when you switch branches?

Whenever you switch to another branch with uncommitted changes (or new files added) in your working tree, these uncommitted changes will also be carried to the new branch that you switch to. Changes that you commit will be committed to the newly switched branch.


1 Answers

git checkout will not run if the checkout would cause any changes to get lost during its process. So even if you use git checkout with a dirty working directory, all your changes are carried over to the other branch. And you can also just switch back to the previous branch to get in the old state.

If the branches are incompatible (for example a file you modified was deleted), git checkout should automatically fail, preventing you from losing any changes.

like image 178
poke Avatar answered Sep 22 '22 07:09

poke