如何检查git在bash脚本中的两个分支之间是否有差异



我需要检查一个bash脚本,如果在一个git存储库中有两个分支之间的差异。我知道有可能看到git diff的差异,但是我需要在中使用它,如果.

我该怎么做呢?

例如:

git diff ......
if [ $? -eq 1 ] 
then
echo "will do something in here"
fi

(编辑:将——exit-code替换为——quiet以抑制输出)

如果存在差异,git diff --quiet将导致命令设置一个类似于普通diff命令的退出码。

if ! git diff --quiet <commit1> <commit2> ; then
echo "Different"
else
echo "Not different"
fi

如果您关心检查特定的错误代码:

git diff --quiet <commit1> <commit2>
case $? in
0) echo "Not different" ;;
1) echo "Different" ;;
128) echo "Invalid commit id(s)" ;;
*) echo "Unknown error" ;;
esac

下面是一个例子:

#!/bin/bash
# Set the branch names
BRANCH1="master"
BRANCH2="my-feature-branch"
# Check if there are differences between the two branches
DIFFERENCES=$(git diff --name-only $BRANCH1 $BRANCH2)
# If there are differences, print a message
if [ -n "$DIFFERENCES" ]; then
echo "There are differences between the $BRANCH1 and $BRANCH2 branches."
else
echo "There are no differences between the $BRANCH1 and $BRANCH2 branches."
fi