Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force pull before push

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)

like image 846
Ali Farhoudi Avatar asked Sep 13 '16 08:09

Ali Farhoudi


People also ask

Can I pull before push?

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.

Should I fetch before push?

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.

How do I force git to pull a file?

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.

How do I force git to push?

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


2 Answers

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.

like image 60
creativeChips Avatar answered Sep 23 '22 19:09

creativeChips


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
like image 44
merlin2011 Avatar answered Sep 21 '22 19:09

merlin2011