简体   繁体   中英

Don't checkout branch after rebase in git

I'm on my branch (not master) and I need to get the latest version of master locally. I do next still staying on my branch:

git fetch
git rebase origin/master master

After this master is checked out and I need to go back to my branch. Is there any way to avoid the check out local master during rebase?

The short answer is unfortunately no .

From the doc :

If is specified, git rebase will perform an automatic git switch before doing anything else. Otherwise it remains on the current branch.

This is the same for merges: you only work on a checked out branch for these operations, since they theretically could result in a conflicting state and would then need to be resolved on the spot.


A sort of workaround would be to chain (with && to stop if the rebase returns an error) the subsequent checkout back in an alias.

# fm for "fresh master"
git config --global alias.fm '!git fetch && git rebase origin/master master && git checkout -'

The accepted answer works most of the time, But if origin/master and master are up to date, the rebase does nothing and using git checkout - will put you back in whatever previous branch.

The solution is to check the diff between the two reference before "rebasing".

Also I think we can make it more generic by using an function alias, ie:

refresh = "!f() { \
  git fetch \
  && git diff origin/$1 $1 \
  || { \
        git rebase origin/$1 $1 \
        && git checkout - \
     ;} \
;}; f"

It is easier to define it directly in the config file because the git config command will try to escape quote and mess thing up.

This way you can do git refresh master or any other branch. If necessary you can rename the alias with a shorter name or use a double alias to have both, ie:

 git config --global alias.rf refresh

Good idea for a alias I'll certainly will be using it. Thanks @vitalii

If you want the changes to be rebased to your branch, you don't need to checkout master . You can stay on your branch and do -

git fetch

and then

git rebase origin/master

This will rebase the commits from your local branch on top of the ones from origin/master . It won't update your local master .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM