Home > Back-end >  git checkout remote branch if it exist, else create it
git checkout remote branch if it exist, else create it

Time:12-03

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?

CodePudding user response:

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).

CodePudding user response:

There is a more concise way to accomplish the same thing as the first line in your code. Instead of using git checkout with the -b flag to create a new branch and then specifying the remote branch to track, you can use the git push command with the -u flag (short for "upstream") to create the new branch and track the remote branch in one step. Here is an example of how you can use this command:

git push -u origin ${BRANCHNAME}

This command will create a new local branch named ${BRANCHNAME} and track the remote branch with the same name. If the remote branch does not yet exist, the command will create it for you. You can then add and commit your changes as usual, and use git push without the -u flag to push your changes to the remote branch.

Here is an example of how you can use this command to combine the first three lines of your code into a single line:

git push -u origin ${BRANCHNAME} && git add ... && git commit -m "new stuff"

This command will create the new branch, add your changes, and commit them in one step. You can then use git push without the -u flag to push your changes to the remote branch.

  • Related