我如何检查我的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声明的那样,它只关心工作树。

其他回答

你也可以

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声明的那样,它只关心工作树。

这个帖子可能会有更好的答案组合。但这对我有用……对于你的.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

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

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

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

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

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

备注:

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

@eduard- wch的回答很完整,但因为我想同时检查两者,这里是我的最后一个变体。

        set -eu

        u="$(git ls-files --others)"
        if ! git diff-index --name-only --quiet HEAD -- || [ -z "${u:-}" ]; then
            dirty="-dirty"
        fi

当不使用set -e或类似的方法执行时,我们可以执行u="$(git ls-files——others)"|| exit 1(如果对已使用的函数有效,则返回)

因此,untracked_files仅在命令成功时设置。

之后,我们可以检查这两个属性,并设置一个变量(或任何东西)。