0

I have a bash script, where I test to see if the git status is clean by checking out a new branch, if I can't do that, I know the status is not clean. However what would be convenient is to just attempt to checkout a new branch but not actually do it, something like:

git checkout --dry -b temp

alternatively, if there is a way to use git status to get an exit code that is non-zero if it's not clean, that would work too.

1 Answer 1

1

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.