我如何检查我的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来避免输出。

你也可以

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状态信息。

我是这么做的:

对于脏状态: 如果当前git分支是脏的,则返回“*”。 函数evil_git_dirty { [[$ (git diff, shortstat 2 > / dev / null |尾巴n1 ) != "" ]] && 回声“*” } 对于未跟踪的文件(请注意git状态的——porcelain标志,它会为您提供良好的可解析输出): 返回未跟踪文件的数量 函数evil_git_num_untracked_files { Expr ' git status——porcelain 2>/dev/null| grep "^??"| wc -l ' }

虽然git diff——shortstat更方便,但你也可以使用git status——porcelain来获取脏文件:

# Get number of files added to the index (but uncommitted)
expr $(git status --porcelain 2>/dev/null| grep "^M" | wc -l)

# Get number of files that are uncommitted and not added
expr $(git status --porcelain 2>/dev/null| grep "^ M" | wc -l)

# Get number of total uncommited files
expr $(git status --porcelain 2>/dev/null| egrep "^(M| M)" | wc -l)

注意:2>/dev/null会过滤掉错误消息,所以你可以在非git目录上使用这些命令。(它们将简单地为文件计数返回0。)

编辑:

以下是这些帖子:

在终端提示中添加Git状态信息

改进了启用git的Shell提示符