有些脚本在检查更改时不能正确工作。

我是这样试的:

VN=$(git describe --abbrev=7 HEAD 2>/dev/null)

git update-index -q --refresh
CHANGED=$(git diff-index --name-only HEAD --)
if [ ! -z $CHANGED ];
    then VN="$VN-mod"
fi

是否存在某种布尔检查,自上次提交以来是否有更改,或者我如何真正测试本地存储库是否有新的更改?

我所做的所有这些都是为了一个版本创建脚本(我在这里的某个地方找到的)。


当前回答

我也遇到了类似的问题,但我还必须检查添加的文件。所以我做了以下事情:

cd /local/repo
RUN=0
git diff --no-ext-diff --quiet --exit-code || RUN=1
if [ $RUN = 0 ]; then
    RUN=`git ls-files --exclude-standard --others| wc -l`
fi

if [ $RUN = 0 ]; then
    exit 0
fi

其他回答

OP的问题已经超过9年了。我不知道那个时候的男人是怎么说的,但现在是这样说的:

--porcelain[=<version>]  
Give the output in an easy-to-parse format for scripts. This is similar to the 
short output, but will remain stable across Git versions and regardless of user 
configuration. See below for details.  

The version parameter is used to specify the format version. This is optional and 
defaults to the original version v1 format.  

这表明,“瓷器”论点非常适合用于测试回购的变化状态。

Wrt OP的问题,“是否有某种布尔检查自上次提交以来是否有更改,或者我如何真正测试本地存储库是否有新的更改?”

我不认为bash本身有布尔数据类型,但这可能足够接近:

[ -z "`git status --porcelain`" ] && echo "NULL-NO DIFFS" || echo "DIFFS EXIST"

这可以作为脚本的if-then-else形式重新转换,或者在git repo文件夹中按原样在CLI中执行。否则,使用-C选项和目标repo的路径规范:

git -C ~/path/to/MyGitRepo status --porcelain 

附录:

有些人建议使用-u,——untracked-file选项来避免报告想要忽略的文件的状态。注意,这带来了一个不幸的副作用:新添加的文件也没有处于状态。该选项在某些情况下是有用的,但在使用前要仔细考虑。

下面是一组很棒的Bash脚本函数,它可以检查是否存在差异,将其打印给用户,并提示用户是否希望在部署之前提交更改。它是为Heroku和Python应用程序构建的,但对于任何其他应用程序,它几乎不需要更改。

commit(){
    echo "Please enter a commit message..."
    read msg
    git add . --all
    git commit -am $msg
}

check_commit(){
    echo ========== CHECKING FOR CHANGES ========
    changes=$(git diff)
    if [ -n "$changes" ]; then
        echo ""
        echo "*** CHANGES FOUND ***"
        echo "$changes"
        echo ""
        echo "You have uncomitted changes."
        echo "Would you like to commit them (y/n)?"
        read n
        case $n in
            "y") commit;;
            "n") echo "Changes will not be included...";;
            *) echo "invalid option";;
        esac
    else
        echo "... No changes found"
    fi
}

deploy(){
    check_commit
    echo ========== DEPLOYING TO HEROKU ========
    git push heroku master
    heroku run python manage.py syncdb
}

你可以从gist上复制:https://gist.github.com/sshadmand/f33afe7c9071bb725105

这工作得很好。它还会列出受影响的文件:

if git diff-index --name-status --exit-code HEAD;
then
    echo Git working copy is clean...;
else
    echo ;
    echo ERROR: Git working copy is dirty!;
    echo Commit your changes and try again.;
fi;

使用git状态:

cd /git/directory
if [[ `git status --porcelain` ]]; then
  # Changes
else
  # No changes
fi

我是这样做的……

CHANGES=`git status | grep "working directory clean"`
if [ ! CHANGES -eq "" ] then
    # do stuff here
else
    echo "You have uncommitted changes..."
fi