如何检查远程存储库是否已更改,是否需要进行拉取?

现在我使用这个简单的脚本:

git pull --dry-run | grep -q -v 'Already up-to-date.' && changed=1

但它相当重。

有没有更好的办法?理想的解决方案是检查所有远程分支,并返回已更改分支的名称以及每个分支中新提交的数量。


当前回答

我只是想把这篇文章作为一个实际的帖子,因为它很容易在评论中错过。

这个问题的正确答案来自@Jake Berger,非常感谢你,每个人都需要这个,每个人都在评论中错过了这个。 因此,对于每个纠结于此的人来说,这里是正确的答案,只需使用该命令的输出来了解是否需要进行git拉取。如果输出为0,那么显然没有什么要更新的。

@stackoverflow,给这家伙一个铃铛。 谢谢@杰克·伯格

# will give you the total number of "different" commits between the two
# Jake Berger Feb 5 '13 at 19:23
git rev-list HEAD...origin/master --count

其他回答

如果你有一个上游分支

git fetch <remote>
git status

如果你没有上游分支

比较这两个分支:

git fetch <remote>
git log <local_branch_name>..<remote_branch_name> --oneline

例如:

git fetch origin

# See if there are any incoming changes
git log HEAD..origin/master --oneline

(我假设原点/主人是你的远程跟踪分支)

如果上面的输出中列出了任何提交,那么您就有了传入的更改——您需要合并。如果git日志中没有列出提交,那么就没有东西可以合并。

注意,即使你在一个没有跟踪远程的特性分支上,这也可以工作,因为if显式地引用了origin/master,而不是隐式地使用Git记住的上游分支。

在阅读了许多答案和多个帖子,并花了半天时间尝试各种排列之后,这就是我想出的。

如果你在Windows上,你可以使用Git for Windows提供的Git Bash在Windows中运行这个脚本(安装或移植)。

这个脚本需要参数

- local path e.g. /d/source/project1
- Git URL e.g. https://username@bitbucket.org/username/project1.git
- password

if a password should not be entered on the command line in plain text,
then modify the script to check if GITPASS is empty; do not
replace and let Git prompt for a password

脚本将会

- Find the current branch
- Get the SHA1 of the remote on that branch
- Get the SHA1 of the local on that branch
- Compare them.

如果脚本打印了更改,那么您可以继续获取或拉取。脚本可能效率不高,但它为我完成了工作。

更新- 2015-10-30:stderr to dev null,防止将URL和密码打印到控制台。

#!/bin/bash

# Shell script to check if a Git pull is required.

LOCALPATH=$1
GITURL=$2
GITPASS=$3

cd $LOCALPATH
BRANCH="$(git rev-parse --abbrev-ref HEAD)"

echo
echo git url = $GITURL
echo branch = $BRANCH

# Bash replace - replace @ with :password@ in the GIT URL
GITURL2="${GITURL/@/:$GITPASS@}"
FOO="$(git ls-remote $GITURL2 -h $BRANCH 2> /dev/null)"
if [ "$?" != "0" ]; then
  echo cannot get remote status
  exit 2
fi
FOO_ARRAY=($FOO)
BAR=${FOO_ARRAY[0]}
echo [$BAR]

LOCALBAR="$(git rev-parse HEAD)"
echo [$LOCALBAR]
echo

if [ "$BAR" == "$LOCALBAR" ]; then
  #read -t10 -n1 -r -p 'Press any key in the next ten seconds...' key
  echo No changes
  exit 0
else
  #read -t10 -n1 -r -p 'Press any key in the next ten seconds...' key
  #echo pressed $key
  echo There are changes between local and remote repositories.
  exit 1
fi

自动化git拉取所需的分支: 例如:./pull.sh "origin/main"

pull.sh

#!/bin/bash

UPSTREAM=${1:-'@{u}'}
DIFFCOMM=$(git fetch origin --quiet; git rev-list HEAD..."$UPSTREAM" --count)
if [ "$DIFFCOMM" -gt 0 ]; then
  echo "Pulling $UPSTREAM";
  git pull;
else
  echo "Up-to-date";
fi

运行git fetch (remote)来更新你的远程引用,它会告诉你什么是新的。然后,当您签出本地分支时,它将显示它是否落后于上游。

命令

git ls-remote origin -h refs/heads/master

将列出远程上的当前头—您可以将其与以前的值进行比较,或者查看您的本地回购中是否有SHA。