Git branch ใช้สำหรับพัฒนาคุณสมบัติแยกจาก main branch เมื่อทำเสร็จและ merge แล้ว ควรลบ branch เพื่อให้ repo สะอาด
โครงสร้างคำสั่ง
git <command> <modifier> <remote_name> <branch_name>
1. ลบ Local Branch
ปลอดภัย (ต้อง merged แล้ว):
git branch -d oldbranch
บังคับลบ (ยังไม่ merged / ไม่ได้ push):
git branch -D oldbranch
หมายเหตุ: ไม่สามารถลบ branch ที่กำลัง checkout อยู่ได้ ต้อง checkout ออกไปก่อน
2. ลบ Remote Branch
Remote name ปกติคือ origin
Git 1.7.0+ (รูปแบบใหม่):
git push origin --delete remotebranch
Git เก่า (รูปแบบเดิม):
git push origin :remotebranch
เครื่องหมาย : หน้า branch name = delete
3. ลบทั้ง Local และ Remote พร้อมกัน (Function/Script)
เพิ่มใน ~/.bashrc หรือ ~/.zshrc:
git-delete-branch() {
local branch=$1
local remote=${2:-origin}
git branch -d "$branch" 2>/dev/null || git branch -D "$branch"
git push "$remote" --delete "$branch"
}
ใช้งาน: git-delete-branch feature-xyz
4. ทำความสะอาด Remote-tracking Branches (Stale)
หลังลบ remote branch แล้ว local ยังมี reference ค้างอยู่ (origin/branchname) ล้างด้วย:
git fetch -p # หรือ git fetch --prune
หรือตั้งค่า auto-prune:
git config --global fetch.prune true
สถานการณ์พิเศษ
- Branch name มี special chars: ใช้ quotes
git branch -d "feature/new-ui" - ลบหลาย branch พร้อมกัน:
git branch -d branch1 branch2 branch3 - Protected branch (GitHub/GitLab): ต้อง unlock ใน web UI ก่อน หรือมีสิทธิ์ admin
Best Practices
- Merge/PR แล้ว → ลบ branch ทันที
- ใช้ naming convention:
feature/,bugfix/,hotfix/,release/ - รัน
git fetch -pเป็นประจำ - CI/CD pipeline ควรมีขั้นตอน cleanup branch
จัดการ branch ให้สะอาด = Git history อ่านง่าย, repo เล็ก, ลดความสับสน!