You need to be more explicit about what you mean.
It's possible to switch branches even if you have uncommitted modifications (sometimes): see Checkout another branch when there are uncommitted changes on the current branch.
It's always possible to create a new branch without changing commits, which is what git checkout -b name
does (unless name
names an existing branch, in which case the checkout fails).
You can have an index that is in an unmerged state. The test for this is to use git write-tree
: if it fails, the index is in an unmerged state.
You can have an index that has files that differ from the HEAD
commit, but is not in an unmerged state, and you can have a work-tree that has files that differ from their HEAD
and/or index copies. Testing these is more complex.
You can have submodules whose status is interesting.
There are tests for several of these conditions in git-sh-setup
, which is found in the git-core directory as located by git --exec-path
:
. $(git --exec-path)/git-sh-setup
require_clean_work_tree "$action"
This will print:
Cannot $action: You have unstaged changes.
or:
Cannot $action: Your index contains uncommitted changes.
(or both, in a more sensible fashion) and return a nonzero error code, as appropriate.