Skip to content
Bash

Git Branches

Branch management and operations.

By EZ4Code Team
gitbranch

Code

#!/bin/bash

# View branches
git branch              # Local branches
git branch -r           # Remote branches
git branch -a           # All branches
git branch -v           # Show last commit

# Create branch
git branch feature      # Create without switch
git checkout -b feature # Create and switch
git checkout -b feature origin/main  # Create from remote
git switch -c feature   # (new command) create and switch

# Switch branch
git checkout main
git switch main         # (new command)
git checkout -          # Switch to previous branch

# Delete branch
git branch -d feature   # Safe delete (merged)
git branch -D feature   # Force delete

# Rename branch
git branch -m old-name new-name
git branch -m new-name  # Rename current branch

# Track remote branch
git branch --set-upstream-to=origin/main main
git branch -u origin/main

# View merged/unmerged
git branch --merged main
git branch --no-merged main

# Branch comparison
git log main..feature       # feature has but main doesn't
git log feature..main       # main has but feature doesn't
git log main...feature      # Differing between both
git diff main...feature     # Compare differences

# Cherry-pick
git cherry-pick <commit-hash>
git cherry-pick --no-commit <hash>  # Don't auto-commit

# Worktree (multiple working dirs)
git worktree add ../project-feature feature
git worktree list
git worktree remove ../project-feature

Explanation

Git branch operations include create, switch, delete, rename, track remote, and compare differences; switch is the recommended new command.

More Bash Snippets