I'm trying to write a shell alias to force push to a contributor's branch on a PR that is currently checked out on my local machine.
I believe the command that needs to be generated is:
git push REMOTE LOCAL_BRANCH:REMOTE_BRANCH --force
The best I can come up with uses git rev-parse --abbrev-ref --symbolic-full-name @{u}
to get REMOTE/REMOTE_BRANCH
, and then cuts it up to generate the push command:
alias forcepr="git push $(git rev-parse --abbrev-ref --symbolic-full-name @{u} | cut -d'/' -f1) $(git rev-parse --abbrev-ref HEAD):$(git rev-parse --abbrev-ref --symbolic-full-name @{u} | cut -d'/' -f2-) --force"
Is there a better (shorter) way?
I have searched for similar questions, and all I found was general questions about the syntax of force push, or advice about the dangers of force push and when it may be warranted. This question is specifically about how to force push to the upstream branch that is already tracked from the local branch (e.g. after pulling with GitHub desktop).
Thanks!
Option 1: Change the default push behavior
git config push.default upstream
Then you can simply use git push
to push to the tracked upstream.
Thanks to @jthill for this solution.
Option 2: Create a shell function
The alias in the question makes the mistake of evaluating rev-parse
when the shell script is interpreted, not when the command is run. This causes it to always push to whichever branch is checked out when the shell loads. Instead, this can be written as a function, which has the benefit of eliminating the duplicate rev-parse
calls:
# push to the current branch's upstream
pushpr() {
remote_fullname=$(git rev-parse --abbrev-ref --symbolic-full-name @{u})
remote=$(echo $remote_fullname | cut -d'/' -f1)
remote_branch=$(echo $remote_fullname | cut -d'/' -f2-)
git push $remote HEAD:$remote_branch "$@"
}