我如何检查我的git存储库中是否有任何未提交的更改:

添加到索引但未提交的更改 无路径的文件

从一个脚本?

git-status在git 1.6.4.2版本中似乎总是返回0。


当前回答

你也可以

git describe --dirty

. 如果它检测到一个肮脏的工作树,它将在结尾附加单词“-dirty”。根据git-describe(1):

   --dirty[=<mark>]
       Describe the working tree. It means describe HEAD and appends <mark> (-dirty by default) if
       the working tree is dirty.

. 注意:未跟踪的文件不被认为是“脏文件”,因为,正如manpage声明的那样,它只关心工作树。

其他回答

VonC答案的实现:

if [[ -n $(git status --porcelain) ]]; then echo "repo is dirty"; fi

这个帖子可能会有更好的答案组合。但这对我有用……对于你的.gitconfig的[alias]部分…

          # git untracked && echo "There are untracked files!"
untracked = ! git status --porcelain 2>/dev/null | grep -q "^??"
          # git unclean && echo "There are uncommited changes!"
  unclean = ! ! git diff --quiet --ignore-submodules HEAD > /dev/null 2>&1
          # git dirty && echo "There are uncommitted changes OR untracked files!"
    dirty = ! git untracked || git unclean

我使用最简单的自动测试来检测脏状态=任何更改,包括未跟踪的文件:

git add --all
git diff-index --exit-code HEAD

备注:

如果没有add——all, diff-index不会注意到未跟踪的文件。 通常情况下,我在测试错误代码后运行git重置来取消所有内容。 考虑用quiet代替exit-code来避免输出。

一个DIY的可能性,更新遵循0xfe的建议

#!/bin/sh
exit $(git status --porcelain | wc -l) 

正如Chris Johnsen所指出的,这只适用于Git 1.7.0或更新版本。

这是最好、最干净的方法。由于某些原因,所选的答案对我不起作用,它没有拾取未提交的新文件所进行的更改。

function git_dirty {
    text=$(git status)
    changed_text="Changes to be committed"
    untracked_files="Untracked files"

    dirty=false

    if [[ ${text} = *"$changed_text"* ]];then
        dirty=true
    fi

    if [[ ${text} = *"$untracked_files"* ]];then
        dirty=true
    fi

    echo $dirty
}