如何在 git diff 命令中显示相对路径?

How to show relative paths in git diff command?

它的工作原理是这样的:

MYPC /d/home/project/some/path (master)
$ git diff --name-only --cached
root.txt
some/path/relative.txt

即它显示了 GIT 根目录的路径,但我需要当前目录的相对路径。

预期结果:

$ git diff --name-only --cached --AND_SOME_OPTION
../../root.txt
relative.txt

按常理来说,应该是git status

P.S. --relative 选项不起作用,因为它将显示来自该目录的文件。 在我们的示例中,它将仅显示 relative.txt.

P.P.S

使用 --git-dir 也不行:

$ git --git-dir=$(git rev-parse --show-toplevel)/.git  diff --cached --name-only
root.txt
some/path/relative.txt

到目前为止,我还没有找到使用相对路径的方法 git-diff

对我有用的唯一方法:

$ git status -s | awk '{print }'
../../root.txt
relative.txt

$ git status -s | cut -c4-

How can I run "git status" and just get the filenames 中解释的最后一种方法。 .第一个很像。 :)

不过最好能找到非流水线的方式。看来,没有办法避免使用--cached。 所以,大多数情况下这不是答案。

git status -s已经输出了可以轻松隔离的相对路径。

如果需要使用 git diff,可以将输出通过管道传输到 realpath,如果可用:

$ git diff --name-only | \
    xargs -I '{}' realpath --relative-to=. $(git rev-parse --show-toplevel)/'{}'
../../root.txt
relative.txt

Joao Delgado 的基础上使用 realpath,您可以使用 --src-prefix--dst-prefix 欺骗 Git 做您想做的事:

$ rel=$(realpath --relative-to=. $(git rev-parse --show-toplevel))
$ git diff --src-prefix=a/$rel/ --dst-prefix=b/$rel/
../../root.txt
../../some/path/relative.txt

这将显示所有修改过的文件(不仅仅是当前工作目录中的文件),并且还将在输出中使用相对路径(尽管对于所有文件)。

请注意,在顶层,这将输出带有前导 ./:

的路径
./root.txt
./some/path/relative.txt

配置 df 别名的方法如下:

$ git config --global alias.df '!f() { : git diff ; rel=$(realpath --relative-to="$PWD/$GIT_PREFIX" "$PWD"); git diff --src-prefix="a/$rel/" --dst-prefix="b/$rel/" "$@"; }; f'
$ git df
../../root.txt
../../some/path/relative.txt

(这使用空命令 : 启用 git diff Bash 完成此别名(参见 https://github.com/git/git/blob/1a4874565fa3b6668042216189551b98b4dc0b1b/contrib/completion/git-completion.bash#L26-L30