Every time I want to push my commits (git commit -m "message"
, git push origin <branch>
), I do a pull (git pull origin <branch>
).
Is there any way to make git do a pull before performing my push? (on the same branch)
Always Pull Before a Push This is a bedrock rule. Before you try to push code out to the repository, you should always pull all the current changes from the remote repository to your local machine. Doing so will ensure that your local copy is in sync with the remote repository.
It's important to fetch and pull before you push. Fetching checks if there are any remote commits that you should incorporate into your local changes. If you see any, pull first to prevent any upstream merge conflicts.
git pull --force it feels like it would help to overwrite local changes. instead, it fetches forcefully but does not merge forcefully ( git pull --force = git fetch --force + git merge ). Like git push, git fetch allows us to specify which local and remote branch we want to work on.
To force a push to only one branch, use a + in front of the refspec to push (e.g git push origin +master to force a push to the master branch).
The Git way to do this is with customize Git hooks.
In your case, you will need to go to the .git/hooks
directory on your repository, and add a file named pre-push
, which is a script of your choice, e.g. (bash in this example)
#!/bin/bash
echo "pulling ..."
git pull
This script will be called when you do git push
and before the actual push.
Obviously, this is just a very naive sample, but I hope you get the idea. There are samples in this directory already. Comment if anything still unclear.
Based on the OP's comments, they appear to be trying to avoid a merge commit between their recent commits and the commits on the remote, which is normally generated by a git pull
when the local and remote histories have diverged.
The explicit way to do this is to first fetch and the rebase, and finally push.
git fetch
git rebase origin/master
git push
A second way to do this is to pass --rebase
when invoking git pull
.
git pull --rebase
Finally, one can make this the default behavior of git pull
by setting the configuration.
git config --global pull.rebase true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With