linux - 验证文件仅在两次提交之间的末尾被修改

标签 linux git gitlab

我的存储库中有一个文件,我只想在末尾插入。
我可以使用哪个linux命令来验证两次git commit之间的文件仅在最后修改?

最佳答案

没有Git命令可以执行此操作,但是您可以在Bash(或您选择的shell)中编写脚本:
您可以创建执行此操作的脚本:

#!/bin/bash

# Create a file which is a version of your file of interest before last commit

git --no-pager show HEAD~:<file> > original

# Get the number of lines for that file and call it n:

n=$(cat original | wc -l)

# Test whether the last commit modified the file other than
# by adding content at the end

[[ "$(diff <(cat original) <(head -$n <file>))" == "" ]]

# Finally, clean up by deleting the temp file:

rm original
如果仅在文件末尾(或根本没有修改),则返回0;如果要阻止的修改(即末尾),则返回1。
当然,您需要将<file>替换为目标文件的路径。
如果您感兴趣的2个提交不是最后2个提交,则可以将脚本修改为更通用。例如,在这里,我将对2个提交使用<hash1><hash2>,但是您可以使用任何方便识别任何2个提交的引用:
#!/bin/bash

# Create a file which is a version of your file of interest at the first commit
# you care about (using its hash):

git --no-pager show <hash1>:<file> > original

# Create a file which is a version of your file of interest at the second commit
# you care about (using its hash):

git --no-pager show <hash2>:<file> > next

# Get the number of lines for the first of these files and call it n:

n=$(cat original | wc -l)

# Test whether the commit with hash2 modified the file other
# than by adding content at the end

[[ "$(diff <(cat original) <(head -$n next))" == "" ]]

# Finally, clean up by deleting the 2 temp files:

rm original next
另外,为了方便起见,由于您可能需要经常在管道中进行测试,因此可以创建一个函数并将其添加到.bashrc或等效项中:
function check {
    local n
    git --no-pager show "$2":"$1" > original
    git --no-pager show "$3":"$1" > next
    n=$(cat original | wc -l)
    [[ "$(diff <(cat original) <(head -$n next))" == "" ]]
    rm original next
}
然后可以将其用于:
check <file-path> <commit-hash1> <commit-hash2>

关于linux - 验证文件仅在两次提交之间的末尾被修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64286676/

相关文章:

linux - 在没有安装任何东西的情况下运行 Ubuntu 使用 512MB 中的 500 我应该杀死哪个进程?

linux - 使用 rsync 下载并使用 gunzip 解压,然后将所有内容放在一个管道中

eclipse - 在 Eclipse IDE 的 EGit 中提交时选择较早的提交消息?

git - pull/推到 Gitlab 错误部署正在进行中

git - 可以在一台机器上使用 GitHub 和 GitLab 吗?

linux - 我想在 linux 上删除多行文本

python - 从 uwsgi 调用子进程 sudo

git 初始化远程仓库

windows - 在 Windows 中的 Git bash 中全局运行 shell 脚本

gitlab - 在 Gitlab CI 中读取 webhook 负载