With the variety of Default Branch choices in git, how can I write a script/alias which references the default branch no matter the name?
My specific example is my alias which rebases onto the newest remote master:
### version for `master`
# rebaseOn = "!f() { BRANCH=$(git symbolic-ref --short HEAD) && git fetch && git pull --rebase; git rebase origin/${1:-master}; }; f"
### version for `main`
rebaseOn = "!f() { BRANCH=$(git symbolic-ref --short HEAD) && git fetch && git pull --rebase; git rebase origin/${1:-main}; }; f"
usage: git rebaseOn
or git rebaseOn newParentBranch
(because its defaulting the input ${1:-main}
)
I would like that command to work for either version there, because various repositories I work with have main
or master
or default
or trunk
So far I've found https://stackoverflow.com/a/50056710/356218: git remote show upstream | grep "HEAD branch" | sed 's/.*: //'
but that is quite long for inserting into an alias.
Is there a better option than that?
Best answer so far
Restating the current best answer in my own words:
@matt suggesting of using git branch --set-upstream-to
:
- I suppose you set
git branch --set-upstream-to <main/master>
when you initially clone a repo, and be very consistent about running that command with every repo you touch - So then you can ignore what github or such says is the default master, and know that on this setup of yours, you always use your preference locally
- As opposed to pair programming or anything where you must fall back to standard behavior
- Then before rebasing onto
default
, you mustpull
your choice of name (script this) so that any new commits are included before the rebase- So if you're using a branch to work in parallel with working on something else on
default
you can't really do that ever with this method, always need a separate branch for commits which aren't ready to push yet
- So if you're using a branch to work in parallel with working on something else on
- Then you can merge into
default
and push without extra work
Merging works mildly better probably (as is always the case with git)
Note: the real frustration is when a repo has both a master
and main
branch, and its difficult to remember/know/discover which is the primary via CLI (have to git log
and look at dates, remember fairly obscure commands, or check github. All those take more than 2 seconds and a context change, to give an idea of the level of the frustration)