How to check if remote branch exists on a given remote repository?

后端 未结 14 1000
独厮守ぢ
独厮守ぢ 2020-12-02 11:04

I need to do a subtree merge for a specific branch, if it exists on a given remote repository. The problem is that the remote repository is not checked out locally, so I can

14条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 11:20

    I'm combining some of the answers above in a script:

    BRANCHES=(develop master 7.0 7.0-master)
    ORIGIN=bitbucket
    REMOTE=github
    
    for BRANCH in "${BRANCHES[@]}"; do
      BRANCH=$(git ls-remote --heads "${ORIGIN}" "${BRANCH}" \
          | cut --delimiter=$'\t' --fields=2 \
          | sed 's,refs/heads/,,' \
          | grep --line-regexp "${BRANCH}")
      if [ -n "${BRANCH}" ]
      then
        git branch --force "${BRANCH}" "${ORIGIN}"/"${BRANCH}"
        git checkout "${BRANCH}"
        git push "${REMOTE}" "${BRANCH}"
      fi
    done
    
    git push github --tags
    

    This script will get 4 branches from a remote bitbucket, and push them to a remote github, and will then push all tags to github. I'm using this in a Jenkins job, that's why you don't see any git fetch or git pull, that is already done in the Jenkins job repository config.

    I usually prefer long-form options in scripts. I could have combined git branch and git checkout by using git checkout -B.

提交回复
热议问题