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

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

从一个脚本?

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


当前回答

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

其他回答

我经常需要一种简单的方法让构建失败,如果在执行结束时有任何被修改的跟踪文件或任何未被忽略的未跟踪文件。

这对于避免构建产生剩余的情况非常重要。

到目前为止,我使用的最好的命令是这样的:

 test -z "$(git status --porcelain | tee /dev/fd/2)" || \
     {{ echo "ERROR: git unclean at the end, failing build." && return 1 }}

它可能看起来有点复杂,如果有人能找到一个短的变种,我会很感激 保持所期望的行为:

如果一切正常,则没有输出和成功退出代码 如果失败,退出代码1 stderr上的错误消息解释了它失败的原因 显示导致失败的文件列表,再次stderr。

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

将分析该命令的输出 是否会根据需要返回适当的错误代码

这样,您就可以在脚本中使用“增强”状态。


正如0xfe在他的精彩回答中提到的,git状态—瓷器在任何基于脚本的解决方案中都是重要的

--porcelain

为脚本提供稳定、易于解析的输出格式。 目前这与——short输出相同,但保证将来不会更改,因此对脚本是安全的。

你也可以

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 add --all
git diff-index --exit-code HEAD

备注:

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