my-notes

Creating_and_Checking_Out_Branches

1 min read

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 main branch.


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 main branch.


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

Check Current Branch
git branch --show-current
Show Branch Graph
git log --oneline --graph --all


#git #branch #switch #checkout

Built with mdgarden