How to check if there's nothing to be committed in the current branch?

后端 未结 9 1131
既然无缘
既然无缘 2020-12-22 15:57

The goal is to get an unambiguous status that can be evaluated in a shell command.

I tried git status but it always returns 0, even if there are items

相关标签:
9条回答
  • 2020-12-22 16:55

    Not pretty, but works:

    git status | grep -qF 'working directory clean' || echo "DIRTY"
    

    Not sure whether the message is locale dependent, so maybe put a LANG=C in front.

    0 讨论(0)
  • 2020-12-22 16:56

    The return value of git status just tells you the exit code of git status, not if there are any modifications to be committed.

    If you want a more computer-readable version of the git status output, try

    git status --porcelain
    

    See the description of git status for more information about that.

    Sample use (script simply tests if git status --porcelain gives any output, no parsing needed):

    if [ -n "$(git status --porcelain)" ]; then
      echo "there are changes";
    else
      echo "no changes";
    fi
    

    Please note that you have to quote the string to test, i.e. the output of git status --porcelain. For more hints about test constructs, refer to the Advanced Bash Scripting Guide (Section string comparison).

    0 讨论(0)
  • 2020-12-22 16:59

    From the git source code there is a sh script which includes the following.

    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 sniplet shows how its possible to use git diff-files and git diff-index to find out if there are any changes to previously known files. It does not however allow you to find out if a new unknown file has been added to the working tree.

    0 讨论(0)
提交回复
热议问题