如何检查远程存储库是否已更改,是否需要进行拉取?
现在我使用这个简单的脚本:
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
但它相当重。
有没有更好的办法?理想的解决方案是检查所有远程分支,并返回已更改分支的名称以及每个分支中新提交的数量。
当前回答
下面的脚本运行良好。
changed=0
git remote update && git status -uno | grep -q 'Your branch is behind' && changed=1
if [ $changed = 1 ]; then
git pull
echo "Updated successfully";
else
echo "Up-to-date"
fi
其他回答
如果你有一个上游分支
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记住的上游分支。
下面是一个Bash一行代码,比较了当前分支的HEAD提交哈希和它的远程上游分支,不需要大量的git获取或git拉取——需要干运行操作:
[ $(git rev-parse HEAD) = $(git ls-remote $(git rev-parse --abbrev-ref @{u} | \
sed 's/\// /g') | cut -f1) ] && echo up to date || echo not up to date
以下是这条有点密集的线是如何被分解的:
Commands are grouped and nested using $(x) Bash command-substitution syntax. git rev-parse --abbrev-ref @{u} returns an abbreviated upstream ref (e.g. origin/master), which is then converted into space-separated fields by the piped sed command, e.g. origin master. This string is fed into git ls-remote which returns the head commit of the remote branch. This command will communicate with the remote repository. The piped cut command extracts just the first field (the commit hash), removing the tab-separated reference string. git rev-parse HEAD returns the local commit hash. The Bash syntax [ a = b ] && x || y completes the one-liner: this is a Bash string-comparison = within a test construct [ test ], followed by and-list and or-list constructs && true || false.
自动化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
现在你也可以找到一个Phing脚本。
我需要一个解决方案来自动更新我的生产环境,我们非常高兴感谢我分享的这个脚本。
脚本是用XML编写的,需要Phing。
对于那些在这个问题上寻找答案的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')
}