Creates, lists, and deletes branches.
Option | Description |
---|---|
-a, --all | Display all branches (including remote branches) |
-d, --delete | Delete a branch |
-D | Force delete a branch |
-m, --move | Rename a branch |
-v, --verbose | Display the latest commit for each branch |
Examples:
git branch
- List local branchesgit branch feature
- Create a new branchgit branch -a
- List all branches (including remote branches)git branch -d feature
- Delete a merged branchgit branch -D feature
- Force delete a branch regardless of merge statusgit branch -m old-name new-name
- Rename a branch
Switches branches or restores files in the working directory.
Option | Description |
---|---|
-b <branch-name> | Create a new branch and switch to it |
-B <branch-name> | Create a new branch if it doesn't exist, or reset it if it exists, then switch to it |
-f, --force | Force switch even if there are uncommitted changes (changes will be lost) |
-- | Separator to distinguish between file paths and branch names |
Examples:
git checkout develop
- Switch to the develop branchgit checkout -b feature
- Create a new feature branch and switch to itgit checkout -- file.txt
- Discard changes to file.txt (restore to the state of the last commit)git checkout HEAD~1 file.txt
- Restore file.txt to the state from one commit beforegit checkout origin/main
- Switch to the state of the remote main branch
A dedicated command for switching branches (splits functionality from checkout).
Option | Description |
---|---|
-c <branch-name> | Create a new branch and switch to it |
-C <branch-name> | Create a new branch if it doesn't exist, or reset it if it exists, then switch to it |
-d, --detach | Switch to a specific commit (detached HEAD state) |
--discard-changes | Discard uncommitted changes when switching |
Examples:
git switch main
- Switch to the main branchgit switch -c feature
- Create a new feature branch and switch to itgit switch -C feature
- Create a new feature branch if it doesn't exist, or reset it if it exists, then switch to itgit switch -d HEAD~3
- Switch to the commit three commits before HEAD (detached HEAD state)git switch -
- Return to the previous branch