这里有很多答案,但没有一个使用git-fetch
来直接更新本地引用的,这比检出分支简单得多,也比使用git-update-ref
更安全。
在这里,我们使用git-fetch
来更新非当前分支,对于当前分支则使用git pull --ff-only
。它:
- 不需要检出分支
- 只在可以快进的情况下更新分支
- 当无法快进时会报告错误
以下是代码:
#!/bin/bash
currentbranchref="$(git symbolic-ref HEAD 2>&-)"
git branch -r | grep -v ' -> ' | while read remotebranch
do
remote="${remotebranch%%/*}"
branchref="refs/heads/${remotebranch#*/}"
if [ "$branchref" == "$currentbranchref" ]
then
echo "Updating current branch $branchref from $remote..."
git pull --ff-only
else
echo "Updating non-current ref $branchref from $remote..."
git fetch "$remote" "$branchref:$branchref"
fi
done
git-fetch
的手册页面上写道:
<refspec>
The format of a <refspec> parameter is an optional plus +, followed by the source ref <src>,
followed by a colon :, followed by the destination ref <dst>.
The remote ref that matches <src> is fetched, and if <dst> is not empty string, the local ref
that matches it is fast-forwarded using <src>. If the optional plus + is used, the local ref is
updated even if it does not result in a fast-forward update.
通过指定git fetch <remote> <ref>:<ref>
(不带任何+
),我们可以获得一个仅在可以快进时更新本地引用的获取。
请注意,这假设本地和远程分支具有相同的名称(并且您想要跟踪所有分支),它应该真正使用关于您拥有哪些本地分支以及它们如何设置跟踪的信息。