在Makefile中,如果有未提交的更改(在工作树或索引中),我希望执行某些操作。最干净、最有效的方法是什么?在一种情况下退出时返回值为零,而在另一种情况下返回值为非零的命令适合我的目的。

我可以运行git状态并通过grep管道输出,但我觉得一定有更好的方法。


当前回答

这是最好、最干净的方法。

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
}

其他回答

使用python和GitPython包:

import git
git.Repo(path).is_dirty(untracked_files=True)

如果存储库不干净,则返回True

正如在另一个回答中指出的那样,这样简单的命令就足够了:

git diff-index --quiet HEAD --

如果省略最后两个破折号,如果文件名为HEAD,则命令将失败。

例子:

#!/bin/bash
set -e
echo -n "Checking if there are uncommited changes... "
trap 'echo -e "\033[0;31mFAILED\033[0m"' ERR
git diff-index --quiet HEAD --
trap - ERR
echo -e "\033[0;32mAll set!\033[0m"

# continue as planned...

警告:此命令忽略未跟踪的文件。

Git diff——exit-code如果有任何变化将返回非零;Git diff——quiet是相同的,没有输出。由于您希望检查工作树和索引,请使用

git diff --quiet && git diff --cached --quiet

Or

git diff --quiet HEAD

其中任何一个都将告诉您是否存在暂存的未提交更改。

工作树是“干净的”,如果

git ls-files \
  --deleted \
  --modified \
  --others \
  --exclude-standard \
  -- :/

返回什么。

解释

——deleted检查工作树中已删除的文件 ——modified检查工作树中修改的文件 ——其他检查文件添加到工作树 ——根据通常的.gitignore, .git/info/exclude…规则 ——:/ pathspec的一切,如果不是运行在存储库的根

如果工作树是干净的,则输出为空

这是最好、最干净的方法。

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
}