Can “git pull --all” update all my local branches?

前端 未结 25 2459
失恋的感觉
失恋的感觉 2020-11-22 16:33

I often have at least 3 remote branches: master, staging and production. I have 3 local branches that track those remote branches.

Updating all my local branches is

25条回答
  •  被撕碎了的回忆
    2020-11-22 17:18

    There are a lot of answers here but none that use git-fetch to update the local ref directly, which is a lot simpler than checking out branches, and safer than git-update-ref.

    Here we use git-fetch to update non-current branches and git pull --ff-only for the current branch. It:

    • Doesn't require checking out branches
    • Updates branches only if they can be fast-forwarded
    • Will report when it can't fast-forward

    and here it is:

    #!/bin/bash
    currentbranchref="$(git symbolic-ref HEAD 2>&-)"
    git branch -r | grep -v ' -> ' | while read remotebranch
    do
        # Split / into remote and branchref parts
        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
    

    From the manpage for git-fetch:

       
           The format of a  parameter is an optional plus +, followed by the source ref ,
           followed by a colon :, followed by the destination ref .
    
           The remote ref that matches  is fetched, and if  is not empty string, the local ref
           that matches it is fast-forwarded using . If the optional plus + is used, the local ref is
           updated even if it does not result in a fast-forward update.
    

    By specifying git fetch : (without any +) we get a fetch that updates the local ref only when it can be fast-forwarded.

    Note: this assumes the local and remote branches are named the same (and that you want to track all branches), it should really use information about which local branches you have and what they are set up to track.

提交回复
热议问题