Creating_and_Checking_Out_Branches
Creating and Checking Out Branches
Create, switch, and manage Git branches.
πΏ Creating Branches
Create Branch
git branch feature-login
Creates new branch but stays on current branch.
Create and Switch
git checkout -b feature-login
Creates new branch and switches to it.
Modern: Create and Switch
git switch -c feature-login
Modern command to create and switch.
Create from Specific Commit
git branch feature-login abc1234
Creates branch starting from specific commit.
Create from Another Branch
git branch feature-login main
Creates branch from
mainbranch.
Create from Tag
git checkout -b hotfix-1.0.1 v1.0.0
Creates branch from a tag.
π Switching Branches
Switch Branch
git checkout main
Switches to
mainbranch.
Modern: Switch Branch
git switch main
Modern way to switch branches.
Switch to Previous Branch
git checkout -
Switches to the branch you were previously on.
Modern: Previous Branch
git switch -
Modern way to switch to previous branch.
Force Switch (Discard Changes)
git checkout -f main
β οΈ Switches and discards uncommitted changes.
π Viewing Branches
List Local Branches
git branch
Shows all local branches. Current branch marked with *.
List with Last Commit
git branch -v
Shows branches with last commit info.
List All Branches (Including Remote)
git branch -a
Shows local and remote-tracking branches.
List Remote Branches Only
git branch -r
Shows only remote-tracking branches.
List Merged Branches
git branch --merged
Shows branches merged into current branch.
List Unmerged Branches
git branch --no-merged
Shows branches not yet merged.
π Branch Lifecycle
graph LR
A[Create Branch] --> B[Work on Branch]
B --> C[Push to Remote]
C --> D[Create PR]
D --> E[Merge]
E --> F[Delete Branch]
βοΈ Renaming Branches
Rename Current Branch
git branch -m new-name
Renames the current branch.
Rename Specific Branch
git branch -m old-name new-name
Renames a branch while on different branch.
Rename on Remote
git push origin --delete old-name
Delete old branch on remote.
git push -u origin new-name
Push renamed branch.
ποΈ Deleting Branches
Delete Local Branch
git branch -d feature-login
Deletes branch only if merged.
Force Delete Local Branch
git branch -D feature-login
β οΈ Force deletes even if unmerged.
Delete Remote Branch
git push origin --delete feature-login
Deletes branch on remote.
Prune Deleted Remote Branches
git fetch --prune
Removes local tracking branches for deleted remotes.
π§Ή Cleanup
Delete All Merged Branches
git branch --merged main | grep -v main | xargs git branch -d
Deletes all branches merged into main.
π‘ Tips
git branch --show-current
git log --oneline --graph --all
π Related
#git #branch #switch #checkout