A branch is a movable name that points to a commit. When you commit on a branch, the name moves forward. This lets you try an idea without disturbing the main line of work.
See your branches
$ git branch
* mainThe * marks the branch you are on. Yours may be master.
Create and switch
$ git switch -c login-page
Switched to a new branch 'login-page'-c creates the branch and moves you to it. To move to an existing branch, use git switch main. git switch appeared in Git 2.23. On older versions, and in many guides, you will see git checkout -b login-page and git checkout main.
git branch login-page creates a branch but leaves you where you are.
Commits stay on their branch
Commit something on login-page, then switch back to main. The files return to how main has them. Your work is not lost; it is on the other branch.
Uncommitted edits are different. Git carries them with you when it safely can, and refuses to switch if switching would overwrite them. Commit before you switch to keep things simple.
Merge the work
Switch to the branch that should receive the changes, then merge the other one into it:
$ git switch main
$ git merge login-page
Updating a07b3f5..c91d044
Fast-forwardA fast-forward happens when main has no new commits of its own, so Git just moves the name forward. If both branches gained commits, Git usually creates a merge commit.
If both sides changed the same lines, you get a conflict. Git marks the spot in the file with <<<<<<<, ======= and >>>>>>>. Edit the file to the result you want, remove the markers, run git add on it, then git commit. Run git merge --abort to back out instead.
Delete a finished branch
$ git branch -d login-pageLowercase -d refuses to delete a branch that is not fully merged (into its upstream branch if it has one, otherwise into the branch you are on). Capital -D forces it, and you can lose track of those commits.
Read more in the git branch documentation.
Try it
Create a branch, commit a new file there, switch back and confirm the file is gone from view. Merge the branch, then delete it with -d.
Check your understanding
Git Branches
All 3 sections · no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.