Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git checkout remote branch if it exist, else create it

I can't be the first one to ask this, but I'm having trouble finding the right search results. These terms are so overloaded.

Eventually I want to make some additions to a remote branch. Remote branch may not exist. So first I clone remote repo, I only have default branch locally. Then:

so far I have:

git checkout -b ${BRANCHNAME} origin/${BRANCHNAME} --track || git checkout -b ${BRANCHNAME}
git add ...
git commit -m "new stuff"
git push origin ${BRANCHNAME}

Is there a nicer way to do the first line?

like image 550
RaGe Avatar asked Oct 23 '25 08:10

RaGe


1 Answers

All branches must have a starting point; your sequence:

  • attempt to create branch B at origin/B with origin/B as upstream;
  • if that fails, create branch B at HEAD with no upstream

can be rewritten as:

if start=$(git rev-parse refs/remotes/origin/${BRANCHNAME}); then
    extra="--track origin/${BRANCHNAME}"
else
    start=HEAD
    extra=
fi
git checkout -b ${BRANCHNAME} ${start} $extra

(or the equivalent with git switch -c as the final command). But I don't think it can be made any shorter than the two-step || variant you already have.

Using the if ... then ... else ... fi sequence, you can add --quiet --verify to the rev-parse step and avoid generating error messages, and of course you can also set additional variables as desired so that you can make or early-encode future tests (e.g., decide whether you want to use git push -u for instance).

like image 130
torek Avatar answered Oct 26 '25 23:10

torek