Back to [[git:main-git|git main page]]
Branch allows to develop or correct the project without impacting on the master
===== Main commands =====
To create a new branch, e;g called **devel**, do:
git checkout -b devel
after this command you will be in **devel** branch. To change to an existing branch, just remove **-b**:
git checkout existing_branch
you are now in **existing_branch**.
To check the branch you are in, do:
git branch
To list all branches (local and remote) use:
git branch -a
If instead of **-a**, you put **-l** you get only the local branches. With **-r**, you get only the remote branches. A more detailed list of branches with their status is given by:
git show-branch
**Important note** : if you checkout from one branch to another, you will lose all the not committed changes in the branch you leave.
===== Pull/push from/to specific remote branch =====
Tu pull a branch on remote that does not exist locally, we first create an empty local branch, then we pull by setting the right origin. For example for a remote branch **new_branch** :
git checkout -b new_branch
git pull origin new_branch
Tu push a local branch to remote, we use **--set-upstream** :
git push --set-upstream origin new_branch
===== Working with multiple branches =====
It is sometimes interesting to copy or update files from one branch to another, Before copying files, we have to into the branch you want to put the file. Let's say we want to update file **file1.txt** and folder **fld1** from branch **b1** to branch **b2**
$ git checkout b2
$ git checkout b1 file1.txt
$ git checkout b1 fld1
Note that the copy or update take place in the current path when no path is specified, but relative path can be used too.
Before copying or update files from one branch to another, it may be useful to check the differences.
To get all the differences between branch **b1** and **b2**, do :
$ git diff b1..b2
To only see the files that have change , out can type :
$ git diff b1..b2 | grep "diff --git"
To see the changes on a single file **file1.txt** :
git diff b1..b2 file1.txt
If you expect conflicts will occur when merging branch **b2** into **b1** you can use the previous commands (git diff and git checkout), but it may be interesting to //pre-merge// in a new branch **b2_merge** :
git checkout b2
git checkout -b b2_merge
git merge b1
Here, you can review new code and fix the possible conflicts. An then you can do the //actual// merge.
Note that the commit may have already been executed when resolving the conflicts.
.
git commit -m "pre merge to resolve conflicts" # note : commit may have already been done
git checkout b2
git merge b2_merge
git branch -d b2_merge
git checkout b1
git merge b2