如果文件路径不正确,文件的git diff不会报错

时间:2018-08-29 07:30:34

标签: git git-diff

我知道在git中我可以通过执行以下操作来获取文件的git diff

git diff [--options] <commit> <commit> [--] [<path>...]

在我的示例中:

git diff commit1 commit2 -- dirThatDoesNotExist\myFileThatDoesNotExist.txt

如果路径(myFileThatDoesNotExist.txt)是不存在的文件,则我似乎没有从git收到错误或任何其他指示,只是没有响应。

获得空响应与有效文件中没有任何更改/差异是无法区分的。

如何获得一条错误消息,指出文件路径不正确,或者通过其他方法来区分文件名错误和有效文件名中没有更改/差异?

1 个答案:

答案 0 :(得分:0)

您可以通过git rev-parse commit:path测试提交中是否存在文件。

git rev-parse commit1:myFileThatDoesNotExist.txt

如果myFileThatDoesNotExist.txt中存在commit1,则该命令返回其blob sha1值,退出代码为0。如果不存在,则返回commit1:myFileThatDoesNotExist.txt,其错误代码为退出代码128,并且错误消息被放入标准错误中,说fatal: Path 'myFileThatDoesNotExist.txt' does not exist in 'commit1'

if git rev-parse commit1:myFileThatDoesNotExist.txt || git rev-parse commit2:myFileThatDoesNotExist.txt;then
    # exist in one of the two commits or in both
    git diff commit1 commit2 -- myFileThatDoesNotExist.txt
else
    # exist in neither, do something else
    :
fi
相关问题