0

Is there a way in Git Bash to check if the working tree is clean, that is no uncommitted changes or untracked files?

I'm working on a bash script for my group to automate the process of daily rebasing working branches. Unclean working trees is a common problem. I can manually correct the problem by executing git checkout .. This would have the desired result most of the time, but not always, so I need to be able to have my script programatically check that the working directory/tree is clean.

3
  • git help clean may be of interest. Commented May 5, 2015 at 21:47
  • "git status" might be useful, too. Commented May 5, 2015 at 22:02
  • git status (specifically the --porcelain option for machine parsing) can give you this information. Commented May 5, 2015 at 22:03

1 Answer 1

1

The git-sh-setup script included with git contains a number of useful functions for working with git repositories. Among them is require_clean_work_tree:

require_clean_work_tree () {
    git rev-parse --verify HEAD >/dev/null || exit 1
    git update-index -q --ignore-submodules --refresh
    err=0
    if ! git diff-files --quiet --ignore-submodules
    then
        echo >&2 "Cannot $1: You have unstaged changes."
        err=1
    fi
    if ! git diff-index --cached --quiet --ignore-submodules HEAD --
    then
        if [ $err = 0 ]
        then
            echo >&2 "Cannot $1: Your index contains uncommitted changes."
        else
            echo >&2 "Additionally, your index contains uncommitted changes."
        fi
        err=1
    fi
    if [ $err = 1 ]
    then
        test -n "$2" && echo >&2 "$2"
        exit 1
    fi
}

This is in addition to being able to check the output from git status --porcelain and/or git status -z if you need to be more specific about what the state currently is.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.