git 忽略换行符和空格更改的状态

git status to ignore newline and whitespace changes

我目前在 markdown 文件中维护我的笔记,但如果我打开现有文件,我使用的编辑器 (marktext) 会添加新的空行。

git 跟踪添加的新空行,并且 git 一直将这些文件显示为修改后的文件。有没有办法配置 git 在执行 git status 时不跟踪这些类型的更改,例如换行符和尾随空格?因为当我对这些特定文件执行 git diff --ignore-all-space --ignore-blank-lines <path-to-file> 时,它根本没有显示任何更改。

提前致谢。

我不知道如何配置 git 来执行您想要的操作。也许这是不可能的(但我相信人们会证明我错了)。但至少你可以稍微破解它并拥有你想要的东西。

您可以创建一个小脚本来检查 git diff --ignore-all-space --ignore-blank-lines 是否会 return 什么,然后输出标准的 nothing to commit, working tree clean 字符串,或者做一个真正的 git status.

#!/bin/bash

diff=$(git diff --ignore-blank-lines --ignore-all-space)

if [[ -z $diff ]];
then
    echo -e "On branch $(git branch --show-current)\nnothing to commit, working tree clean"
else
    git status
fi

然后你可以像调用 git 命令一样调用这个脚本,如果你把它放在你的 global/local .gitconfig

# git config stuff
[alias]
    nw-status = "!p() { bash ~/path/to/script/git-nw-status.sh ; }; p"

注意这不是您想要的。如果您确实有非空白非换行的更改,那么您将看到 git status 但是通过检查 git diff 您还必须使用其他命令来忽略空白和换行。这可能会给您带来不便。

您可以设置一个 clean content filter driver as here,它将自动删除 git diff/git commit 上的那些尾随空行。

图片来自“Keyword Expansion" section of the "ProGit book

那个干净的脚本会 trim any trailing empty lines

# Delete all trailing blank lines at end of file (only).
sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba' file