Create a branch to work on your project without yet modifying the original code.
Why branch? Imagine you are working on an issue and have made many changes throughout the code base. Then, you discover you need to quickly fix something small unrelated to your current project. If you are working on the main branch, you will need to either undo everything you've worked on or finish your work before you can push the changes. If you are working on a branch instead, just switch back to the main branch (and maybe create another branch for this issue), make your fix, push your changes, and then come back to what you were working on.
When collaborating with others on the same repo (i.e., without creating a [[fork]]), branching is a way to protect the main branch and good practice.
And hey, if those changes don't work out you can simply delete the branch rather than try to undo everything you just did.
1. Create a branch and check out the branch.
```bash
git branch <branch>
git checkout <branch>
# or in one line
git checkout -b <branch>
```
2. Make changes and commit changes as you would otherwise.
```bash
git add -A
git commit -m "<commit message>"
```
3. Switch back to the `main` branch and merge.
```bash
git checkout main
git merge <branch>
```
4. Finally, delete the merged branch.
```bash
git branch -d <branch>
```
### Working on Github
When working collaboratively on Github, you'll want to push the changes from the branch to the repo and open a [[pull request]] to communicate with your collaborators.
Instead of merging the branch in step 3, push the changes to GitHub.
```bash
git push origin <branch>
```
Then open the branch in GitHub and follow the instructions for merging the [[pull request]] there.
Finally, checkout the main branch in bash, pull the changes from GitHub (your branch is now merged with the main branch), and delete the branch.
```bash
git checkout main
git pull
git branch -d <branch>
```
You can always use `git branch` to see existing branches.
### Changes on `main`
Note that any changes made to the `main` branch will not be reflected on your branch.
You can either deal with the changes when you merge your branch (any [[merge conflicts]] will need to be manually addressed) or you can regularly `pull` changes from the `main` branch after checking out your branch. Ideally, you and your collaborators avoid working on issues that might result in such collisions.
```bash
git checkout <branch>
git merge main
```
> [!example]- Additional Resources
> - [Pro Git: Git Branching and Merging tutorial](https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging)