如何检查远程存储库是否已更改,是否需要进行拉取?
现在我使用这个简单的脚本:
git pull --dry-run | grep -q -v 'Already up-to-date.' && changed=1
但它相当重。
有没有更好的办法?理想的解决方案是检查所有远程分支,并返回已更改分支的名称以及每个分支中新提交的数量。
如何检查远程存储库是否已更改,是否需要进行拉取?
现在我使用这个简单的脚本:
git pull --dry-run | grep -q -v 'Already up-to-date.' && changed=1
但它相当重。
有没有更好的办法?理想的解决方案是检查所有远程分支,并返回已更改分支的名称以及每个分支中新提交的数量。
当前回答
对于那些在这个问题上寻找答案的windows用户,我已经将部分答案修改为powershell脚本。根据需要进行调整,保存到.ps1文件,并根据需要或计划运行。
cd C:\<path to repo>
git remote update #update remote
$msg = git remote show origin #capture status
$update = $msg -like '*local out of date*'
if($update.length -gt 0){ #if local needs update
Write-Host ('needs update')
git pull
git reset --hard origin/master
Write-Host ('local updated')
} else {
Write-Host ('no update needed')
}
其他回答
如果你有一个上游分支
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记住的上游分支。
我认为最好的方法是:
git diff remotes/origin/HEAD
假设您已经注册了this refspec。如果您已经克隆了存储库,则应该这样做,否则(例如,如果回购是在本地从头创建的,并推到远程),则需要显式地添加refspec。
我基于@jberger的评论来解决这个问题。
if git checkout master &&
git fetch origin master &&
[ `git rev-list HEAD...origin/master --count` != 0 ] &&
git merge origin/master
then
echo 'Updated!'
else
echo 'Not updated.'
fi
我建议你去看看脚本https://github.com/badele/gitcheck。我编写了这个脚本,用于一次性检查所有Git存储库,它显示了谁没有提交,谁没有推/拉。
下面是一个示例结果:
我使用了一个基于Stephen Haberman回答的脚本版本:
if [ -n "$1" ]; then
gitbin="git -C $1"
else
gitbin="git"
fi
# Fetches from all the remotes, although --all can be replaced with origin
$gitbin fetch --all
if [ $($gitbin rev-parse HEAD) != $($gitbin rev-parse @{u}) ]; then
$gitbin rebase @{u} --preserve-merges
fi
假设此脚本名为Git -fetch-and-rebase,可以使用本地Git存储库的可选参数目录名来调用它,以执行操作。如果调用脚本时不带参数,则假定当前目录是Git存储库的一部分。
例子:
# Operates on /abc/def/my-git-repo-dir
git-fetch-and-rebase /abc/def/my-git-repo-dir
# Operates on the Git repository which the current working directory is part of
git-fetch-and-rebase
这里也有。