Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git and working on multiple branches

I have a couple of Git branches: 'experimental', 'something' and 'master'.

I switched to the 'experimental' branch. I noticed a bug which is unrelated to 'experimental' and belongs to changes which have been made in 'something'. How should I fix it?

I'm thinking I should switch to 'something', fix the bug, commit and then move back to 'experimental'. How should I take the minor change from 'something' and apply it to both 'master' and 'experimental' so that I don't have to re-fix the bug again when I switch into these branches?

like image 236
Gav Avatar asked Aug 26 '09 11:08

Gav


People also ask

How can I work on multiple branches at the same time?

So you can work on two branches simultaneously. One small catch is that you can't have the same branches checked out in different worktrees. So if you have checked out one branch in one worktree, then the same branch can't be checked out in another different worktree. Another catch is worktrees sync up with each other.

How many branches can you have in git?

There are five different branch types in total: Main.


1 Answers

There are two solutions not mentioned already that you can use: use a topic branch or use cherry-picking.


Topic branch solution

In the topic branch solution, you switch to branch 'something', create a branch to fix a bug e.g. 'something-bugfix', merge this branch into 'something' (fixing the bug), then merge this branch into 'experimental'.

$ git checkout -b something-fix something [edit, commit] $ git checkout something $ git merge something-fix $ git checkout experimental $ git merge something-fix [fix conflicts if necessary and commit] 

See also Resolving conflicts/dependencies between topic branches early and Never merging back, and perhaps also Committing to a different branch blog posts by Junio C Hamano (git maintainer).


Cherry-picking a bugfix

The cherry-picking solution is useful if you noticed later that the bugfix you created (e.g. on development branch) would be useful also on other branch (e.g. stable branch). In your case you would comit a fix on 'something' branch:

$ git checkout something [edit, edit, edit] $ git commit $ git checkout experimental 

Then you noticed that fix you comitted in 'something' branch should be also on 'experimenta' branch. Lets say that this bugfix was commit 'A' (e.g. 'something' if you didn't commit anything on top of 'something', but it might be e.g. 'something~2' or 'c84fb911'):

$ git checkout experimental $ git cherry-pick A 

(you can use --edit option to git cherry-pick if you want to edit commit message before comitting cherry-picked bugfix).

like image 131
Jakub Narębski Avatar answered Sep 23 '22 23:09

Jakub Narębski