Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in DevOps and Agile by (29.3k points)

I work on a project that has 2 branches, A and B. I typically work on branch A and merge stuff from branch B. For the merging, I would typically do:

git merge origin/branchB

However, I would also like to keep a local copy of branch B, as I may occasionally check out the branch without first merging with my branch A. For this, I would do:

git checkout branchB

git pull

git checkout branchA

Is there a way to do the above in one command, and without having to switch branch back and forth? Should I be using git update-ref for that? How?

1 Answer

0 votes
by (50.2k points)

If you are using a fast-forward merge, then you can simply use

git fetch <remote> <sourceBranch>:<destinationBranch>

Examples:

# Merge local branch foo into local branch master,

# without having to checkout master first.

# Here `.` means to use the local repository as the "remote":

git fetch . foo:master

# Merge remote branch origin/foo into local branch foo,

# without having to checkout foo first:

git fetch origin foo:foo

And also, you can work on this using git fetch. 

This way is a little safer than just force-moving the branch reference since git fetch will automatically prevent accidental non-fast-forwards as long as you don't use + in the refspec.

Sometimes, you cannot merge a branch B into branch A without checking out A first if it would result in a non-fast-forward merge. 

This is because a working copy is needed to resolve any potential conflicts.

To do this without checking out a branch first, you can use 

git fetch with a refspec.

git fetch upstream master:master

You'll probably want to make an alias for it in your git configuration file, like this one:

[alias]

    sync = !sh -c 'git checkout --quiet HEAD; git fetch upstream master:master; git checkout --quiet -'

This will help you to push the changes without any checkouts.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...