有没有一种方法可以通过运行一些git命令并检查其退出码来判断一个文件是否正在被跟踪?

换句话说:git在跟踪文件吗?


当前回答

try:

git ls-files --error-unmatch <file name>

如果不跟踪文件,将退出1

其他回答

使用git日志将提供有关此的信息。如果文件在git中被跟踪,该命令会显示一些结果(日志)。否则就是空的。

例如,如果文件被git跟踪,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
commit ad9180b772d5c64dcd79a6cbb9487bd2ef08cbfc
Author: User <someone@somedomain.com>
Date:   Mon Feb 20 07:45:04 2017 -0600

    fix eslint indentation errors
....
....

如果文件没有git跟踪,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
root@user-ubuntu:~/project-repo-directory#

我建议您使用.gitconfig自定义别名。

你必须这样做:

1)使用git命令:

git config --global alias.check-file <command>

2)编辑~/。在alias部分添加这一行:

[alias]
    check-file = "!f() { if [ $# -eq 0 ]; then echo 'Filename missing!'; else tracked=$(git ls-files ${1}); if [[ -z ${tracked} ]]; then echo 'File not tracked'; else echo 'File tracked'; fi; fi;  };  f"

一旦启动命令(1)或保存文件(2),在您的工作空间中,您可以测试它:

$ git check-file
$ Filename missing 

$ git check-file README.md
$ File tracked 

$ git check-file foo
$ File not tracked

try:

git ls-files --error-unmatch <file name>

如果不跟踪文件,将退出1

如果您不想让错误消息弄乱控制台,也可以运行

git ls-files file_name

然后检查结果。如果git没有返回任何内容,则不会跟踪该文件。如果它被跟踪,git将返回文件路径。

如果你想把它合并到一个脚本中,比如PowerShell,这就很方便了:

$gitResult = (git ls-files $_) | out-string
if ($gitResult.length -ne 0)
{
    ## do stuff with the tracked file
}

我的观点是:

Git ls-files | grep -x相对/路径

在自动补全shell中,可以通过按TAB键轻松确定相对/路径。添加额外的| wc -l以获得1或0输出。