dumbledad dumbledad - 1 year ago 50
Git Question

Making a new branch and setting its upstream in one Git command

My usual workflow for making a new branch is

git checkout -b My-New-Branch

and then after some local commits

git push --set-upstream origin My-New-Branch

Looking at the documentation for git checkout it looks like I should be able to use
to set the new upstream branch as I make the local branch, but I cannot seem to make it work: these all fail with the error given.

git checkout --track origin/My-New-Branch
git checkout -b My-New-Branch --track origin/My-New-Branch
git checkout -b My-New-Branch --track origin My-New-Branch
git checkout -b --track origin My-New-Branch

fatal: Cannot update paths and switch to branch 'My-New-Branch' at the
same time.

Did you intend to checkout 'My-New-Branch' which can not
be resolved as commit?

Is it possible to set the upstream as I create a new branch in Git?

Answer Source

You could define an alias to do that:

git config --global alias.co-push '!f() { git checkout -b $1; git push --set-upstream origin $1; }; f'

This will allow you to do git co-push My-New-Branch, which will execute both commands you have been executing separate before. If you need to push to different remotes, you can exchange "origin" with "$2" in the definition and then do git co-push My-New-Branch origin.