คู่มือฉบับสมบูรณ์ - 2025 Edition

คำสั่ง Git

คู่มือใช้งาน Git แบบฉบับสมบูรณ์ สำหรับ DevOps และ Developer

เรียนรู้ Git จากพื้นฐานถึงขั้นสูง พร้อมตัวอย่างการใช้งานจริง คำอธิบายรายคำสั่ง และ เคล็ดลับการใช้งานสำหรับพัฒนาซอฟต์แวร์อย่างมืออาชีพ

Git
Branching
Commit
Collaboration

สารบัญ

บทนำ: Git คืออะไรและทำไมถึงสำคัญ?

Git เป็นระบบควบคุมเวอร์ชันแบบกระจาย (Distributed Version Control System - DVCS) ที่ถูกพัฒนาขึ้นโดย Linus Torvalds ในปี 2005 สำหรับการพัฒนา kernel ของ Linux

ต่างจากระบบควบคุมเวอร์ชันแบบศูนย์กลาง (SVN, CVS) Git ให้ทุกคนมี copy ของ repository เต็มรูปแบบ ทำให้สามารถทำงาน offline ได้ และมีประสิทธิภาพสูงในการจัดการ commit

ข้อดีของ Git

  • การทำงานแบบกระจาย - ไม่ต้องพึ่งพา server เสมอไป
  • Branching & Merging ที่เร็วและง่าย
  • ประวัติการเปลี่ยนแปลงที่สมบูรณ์
  • การสำรองข้อมูลอัตโนมัติทุก commit
  • Community ขนาดใหญ่และเครื่องมือสนับสนุนมากมาย

Git ในอุตสาหกรรมซอฟต์แวร์

GitHub (Microsoft) ใช้งานมากที่สุด
GitLab For DevOps
Bitbucket สำหรับทีม
Gitea Self-hosted

ผู้ที่ควรเรียนรู้ Git

  • 👨‍💻 นักพัฒนา (Developer) - ควบคุมเวอร์ชันโค้ด
  • ⚙️ DevOps Engineer - CI/CD pipelines, deployment
  • 🎨 Designer - จัดการ assets และ design files
  • 📝 Technical Writer - Collaborate on documentation

1. คำสั่งพื้นฐาน Git (Basic Commands)

git init

สร้าง Repository ใหม่

สร้าง Git repository ใหม่ใน directory ปัจจุบัน

bash
# Initialize new Git repository
cd /path/to/your/project
git init

ตัวอย่างการใช้งาน

ใช้เมื่อคุณมีโปรเจคใหม่ที่ต้องการเริ่มควบคุมเวอร์ชัน:

mkdir my-new-project
cd my-new-project
git init

หลังจากนั้นจะมี folder .git/ ถูกสร้างขึ้น ซึ่งเก็บ metadata และ object database ของ repository

git clone

คัดลอก Repository

คัดลอก repository จากระยะไกลมาที่เครื่อง lokale ของคุณ

bash
# Clone remote repository
git clone https://github.com/username/repository.git

# Clone to specific directory
git clone https://github.com/username/repository.git my-project

# Clone with shallow history (last 1 commit only)
git clone --depth=1 https://github.com/username/repository.git

ตัวอย่างจริง

# Clone this repository
git clone https://github.com/your-org/tech-wiki.git

# Shallow clone for CI/CD
git clone --depth=1 https://github.com/your-org/tech-wiki.git

tip: ใช้ --depth=1 สำหรับ CI/CD หรือการ deploy เพื่อลดขนาด repository และเวลา clone

git status

ดูสถานะไฟล์

แสดงสถานะของ repository ว่ามีไฟล์อะไรที่ถูก modify, staged, หรือ untracked

bash
# Show working tree status
git status

# Short format
git status -s

# Show ignored files
git status --ignored

ตัวอย่าง Output

On branch main
Your branch is up to date with 'origin/main'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
	modified:   src/main.py

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	new-file.txt

no changes added to commit (use "git add" and/or "git commit -a")

สีเขียว = เปลี่ยนแปลงแล้วแต่ยังไม่ staging
แดง = ไฟล์ใหม่ที่ยังไม่ถูก track

git add

เพิ่มไฟล์เข้า staging area

เพิ่มไฟล์หรือการเปลี่ยนแปลงของไฟล์เข้า staging area ก่อน commit

bash
# Add specific file
git add filename.txt

# Add multiple files
git add file1.txt file2.py file3.sh

# Add all changes in current directory
git add .

# Add all tracked files with changes
git add -u

# Add all files including new/ignored
git add -A

ตัวอย่างการใช้งาน

# Add only Python files
git add *.py

# Add files matching pattern
git add src/**/*.js

# Interactive mode - choose what to add
git add -p

ข้อควรระวัง

ใช้ git add -A ให้ระมัดระวัง เพราะจะเพิ่ม file ทั้งหมดรวมถึงไฟล์ที่ ignore ไว้

แนะนำให้ใช้ git status ก่อนเสมอ

git commit

บันทึกการเปลี่ยนแปลง

บันทึกการเปลี่ยนแปลงที่ staging area เข้า repository อย่างถาวร

bash
# Commit with message
git commit -m "Your descriptive message"

# Commit all changes (skip staging)
git commit -a -m "Your message"

# Commit with detailed message (opens editor)
git commit

# Squash last N commits into one
git rebase -i HEAD~N

หลักการเขียน Commit Message

รูปแบบ Convention
# Type: subject

- feat: New feature
- fix: Bug fix
- docs: Documentation changes
- style: Code style changes
- refactor: Code refactoring
- test: Adding tests
- chore: Maintenance
ตัวอย่าง
git commit -m "feat: add user authentication"
git commit -m "fix: resolve login timeout issue"
git commit -m "docs: update README with installation steps"

git log

ดูประวัติ commit

แสดงประวัติการ commit ทั้งหมดของ repository

bash
# Show commit history
git log

# Show in one line per commit
git log --oneline

# Show with graph
git log --graph --oneline --all

# Show commits by author
git log --author="Name"

# Show with file changes
git log -p

ตัวกรองที่ใช้บ่อย

--since/--until

Filter by date range

--stat

Show summary statistics

-S "string"

Find commits by content

git diff

เปรียบเทียบการเปลี่ยนแปลง

แสดงการเปรียบเทียบการเปลี่ยนแปลงระหว่าง working tree กับ index หรือระหว่าง commit

bash
# Show unstaged changes
git diff

# Show staged changes
git diff --cached

# Show changes between branches
git diff branch1..branch2

# Show changes in specific file
git diff filename.txt

# Show only file names
git diff --name-only

การอ่าน Diff Output

@@ -1,5 +1,6 @@
 function greeting() {
-  console.log("Hello");
+  console.log("Hello, World!");
   return true;
 }

 // Added line
+console.log("New line");

- = ลบ
+ = เพิ่ม

2. การจัดการ Branch (Branch Management)

git branch

จัดการ branch

สร้าง, ลบ, หรือแสดงรายการ branch

bash
# List all branches
git branch

# List all branches with last commit
git branch -v

# Create new branch
git branch new-feature

# Delete branch
git branch -d feature-branch

# Force delete branch
git branch -D feature-branch

git checkout

สลับ branch

เปลี่ยนไปใช้งาน branch อื่น หรือ กู้คืนไฟล์จาก commit

bash
# Switch to branch
git checkout branch-name

# Create and switch to new branch
git checkout -b new-feature

# Switch to last branch
git checkout -

# Discard changes in file
git checkout -- filename.txt

# Checkout file from specific commit
git checkout commit-hash -- filename.txt

Git Checkout vs Switch

ใน Git เวอร์ชันใหม่ (2.23+) มีคำสั่ง git switch มาแทน:

# Equivalent commands
git checkout branch-name
git switch branch-name

git checkout -b new-feature
git switch -c new-feature

git merge

รวม branch

รวมการเปลี่ยนแปลงจาก branch อื่นเข้ากับ branch ปัจจุบัน

bash
# Merge branch into current
git merge branch-name

# Merge with commit message
git merge branch-name -m "Merge feature branch"

# Fast-forward only (don't create merge commit)
git merge --ff-only branch-name

# Squash merge
git merge --squash branch-name

Types of Merge

Fast-forward merge

Branch ที่ merge มี history น้อยกว่า main

Three-way merge

Merge ที่มีความแตกต่างทั้งสอง branch

git rebase

เปลี่ยน base commit

ย้ายหรือรวม commit series ไปยัง base commit ใหม่ (สร้าง history ที่ cleaner)

bash
# Rebase current branch to main
git rebase main

# Interactive rebase (edit commits)
git rebase -i HEAD~3

# Continue after fixing conflicts
git rebase --continue

# Abort rebase
git rebase --abort

# Skip current patch
git rebase --skip

คำเตือน!

ไม่ควรใช้ git rebase กับ commit ที่ push ไปแล้วบน remote repository เพราะจะเปลี่ยน history และทำให้เกิดปัญหาเมื่อทีมคนอื่นใช้งาน repository เดียวกัน

ใช้เฉพาะกับ local branch หรือ commit ที่ยังไม่ได้ push

โครงสร้าง Branch (Branch Model)

1 2 3 4 5 6 7 bugfix #1 bugfix #2 bugfix #3 feat A feat B feat C main (origin/main) feature/bugfix feature/new-ui

รูปภาพ: โครงสร้าง branch แบบ feature branches พร้อม merge กลับเข้า main

3. Remote Repositories (Remote)

git remote

จัดการ remote

จัดการ list ของ remote repository ที่เชื่อมโยงกับ local repository

bash
# List remote repositories
git remote

# Show remote URL
git remote -v

# Add new remote
git remote add origin https://github.com/username/repo.git

# Remove remote
git remote remove origin

# Rename remote
git remote rename origin upstream

ตัวอย่างการตั้งค่า

# Typical setup for GitHub
git remote add origin https://github.com/your-org/your-repo.git
git remote add upstream https://github.com/original-org/your-repo.git

# Verify setup
git remote -v

git push

ส่ง commit ไป remote

ส่ง commit local ไปยัง remote repository

bash
# Push to remote
git push origin main

# Force push (dangerous!)
git push --force

# Force push with lease (safer)
git push --force-with-lease

# Push all branches
git push --all origin

# Delete remote branch
git push origin --delete branch-name

คำเตือน!

ไม่ควรใช้ git push --force กับ branch สาธารณะ (เช่น main, develop) เพราะจะทำให้ history ของทีมคนอื่นไม่ตรงกับ remote ทำให้เกิดปัญหาใหญ่

ใช้ --force-with-lease แทนเพื่อความปลอดภัย

git pull

ดึงและรวมจาก remote

ดึง commit จาก remote และ merge เข้า branch ปัจจุบัน (equiv. git fetch + git merge)

bash
# Pull from remote
git pull origin main

# Pull with rebase instead of merge
git pull --rebase origin main

# Pull from specific remote branch
git pull origin feature-branch

Pull vs Fetch

git fetch

ดึงข้อมูลมาแต่ไม่ merge อัตโนมัติ

safer สำหรับดู changes ก่อน

git pull

ดึงและ merge อัตโนมัติ

convenient แต่ต้องระวัง conflicts

git fetch

ดึงข้อมูลจาก remote

ดึง commit, refs, และ objects จาก remote repository แต่ไม่ merge

bash
# Fetch from all remotes
git fetch --all

# Fetch from specific remote
git fetch origin

# Prune deleted remote branches
git fetch --prune

# Fetch tags
git fetch --tags

ตัวอย่าง workflow

# 1. Fetch latest changes
git fetch origin

# 2. Check what will be merged
git log main..origin/main

# 3. Preview the merge
git diff main origin/main

# 4. Then merge if satisfied
git merge origin/main

4. Git Workflow (Git Flow)

Git Flow

main develop release/x.y.z hotfix/x.y.z feature/a feature/b merge merge tag

Git Flow ซึ่งเป็น branching model ที่นิยมใช้ในทีมพัฒนาซอฟต์แวร์

Branches หลัก

main/master

Branch หลักที่เก็บ code ที่ deploy ได้จริง แต่ละ release มี tag

develop

Branch สำหรับพัฒนาฟีเจอร์ใหม่ รวมโค้ดที่พร้อม Test

feature/*

Feature branches จาก develop สำหรับพัฒนาฟีเจอร์เฉพาะ

release/*

Branch สำหรับความพร้อม release version ก่อน merge เข้า main

hotfix/*

การแก้ไขฉุกเฉิน branches จาก main เพื่อแก้ปัญหาที่ production

คำสั่ง Git Flow ที่ใช้บ่อย

# Start new feature
git flow feature start my-feature

# Finish feature
git flow feature finish my-feature

# Start release
git flow release start v1.0.0

# Finish release
git flow release finish v1.0.0

# Start hotfix
git flow hotfix start v1.0.1

# Finish hotfix
git flow hotfix finish v1.0.1

ต้องติดตั้ง git-flow ก่อนใช้งาน

5. หลักปฏิบัติที่ดี (Best Practices)

.gitignore

Exclude untracked files

ไฟล์ configuration ที่บอก Git ว่าไฟล์ใดที่ไม่ต้อง track

bash
# Create .gitignore
touch .gitignore

# Check which files are being ignored
git check-ignore -v path/to/file

ตัวอย่าง .gitignore

# OS files
.DS_Store
Thumbs.db
*.swp
*.swo

# IDE
.idea/
.vscode/
.project
.classpath

# Build outputs
node_modules/
dist/
build/
*.pyc
__pycache__/

# Logs
*.log
npm-debug.log*

# Secrets and config
.env
.env.local
.env.*.local

# Dependencies
vendor/
/bower_components/

การเขียน Commit Message

Communication tool

ทำให้ถูกต้อง

  • อธิบายสิ่งที่ change อย่างชัดเจน
  • แบ่ง commit เป็น logically separate
  • อย่า commit code ที่ break build
  • ใช้ conventional commits

อย่าทำ

  • อย่า commit ไฟล์ที่ sensitive (password, API keys)
  • อย่า commit โค้ดที่ยัง debug อยู่
  • อย่า commit binary files ที่ไม่จำเป็น
  • อย่า commit เฉพาะการจัดรูปแบบ (formatting) โดยไม่มี functional change

Branch Naming Conventions

Organization

รูปแบบที่แนะนำ

# Feature branches
feature/feature-name
feat/user-authentication
feat/payment-integration

# Bug fix branches
bugfix/fix-login-issue
fix/authentication-bug

# Hotfix branches
hotfix/security-patch
hotfix/critical-bug

# Release branches
release/v1.0.0
release/2024-q1

# Documentation
docs/update-readme
docs/api-reference

Benefits: ง่ายต่อการเข้าใจ, search, และ filter

Pull Request Best Practices

Code review

Before Submitting PR

  • ✓ Run tests และ pass ทั้งหมด
  • ✓ Code review ของตัวเอง (self-review)
  • ✓ Update documentation หากจำเป็น
  • ✓ Squash ขั้นตอนที่ไม่จำเป็น
  • ✓ PR ควร size เล็ก (max 200-300 lines)

PR Title & Description

# PR Title format
type: short description

# Examples
feat: add OAuth2 authentication
fix: resolve memory leak in cache
docs: update API documentation

# PR Description (GitHub template)
## Description
## Related Issue
## Testing
## Screenshots (if applicable)

6. ปัญหาพบบ่อย & วิธีแก้ไข (Common Issues)

1. Merge Conflict

แก้ไข conflict

เกิดขึ้นเมื่อ Git ไม่สามารถ merge หรือ rebase changes ได้อัตโนมัติ

bash
# Check conflicted files
git status

# After resolving conflicts
git add conflicted-file.txt

# Continue merge
git merge --continue

# Rebase with conflict
git rebase --continue

# Abort operation
git merge --abort
git rebase --abort

ตัวอย่าง Conflict Marker

<<<<<<< HEAD
console.log("Current branch version");
=======
console.log("Feature branch version");
>>>>>>> feature-branch
console.log("End of file");

เปลี่ยน เป็นโค้ดที่ต้องการ แล้วใช้ git add เพื่อ mark as resolved

2. Stashing Changes

_temporarily save changes

ทิ้งการเปลี่ยนแปลงชั่วคราวเพื่อเปลี่ยน branch หรือทำอย่างอื่นก่อน

bash
# Stash current changes
git stash

# Stash with message
git stash save "WIP: Feature X"

# Show all stashes
git stash list

# Apply most recent stash
git stash pop

# Apply specific stash
git stash apply stash@{1}

# Drop stash
git stash drop

Use Cases

  • • ต้องการ switch branch แต่ยังไม่พร้อม commit
  • • ต้องดู quick fixes บน branch อื่น
  • • ทดลองโค้ดใหม่แต่กลัว break current work

3. Reset vs Revert

Undo changes

git reset

เปลี่ยน HEAD และ branch pointer ไปยัง commit ที่ระบุ

# Soft reset (keep changes)
git reset --soft HEAD~1

# Mixed reset (default, keep in working tree)
git reset --mixed HEAD~1

# Hard reset (discard all changes)
git reset --hard HEAD~1

# Reset to specific commit
git reset --hard abc1234

danger: เปลี่ยน history แล้ว! อย่าใช้กับ shared commits

git revert

สร้าง commit ใหม่ที่ undo changes จาก commit ที่ระบุ (ไม่เปลี่ยน history)

# Revert specific commit
git revert HEAD

# Revert multiple commits
git revert HEAD~2..HEAD

# Don't commit the revert
git revert --no-commit HEAD

safely: ปลอดภัยสำหรับ shared repositories

4. กู้คืน Branch ที่ถูกลบ

Recover branches

คุณสามารถกู้คืน branch ที่ถูกลบด้วย git reflog

bash
# Show all actions in reflog
git reflog

# Find the commit hash before deletion
git reflog | grep "branch: Created from"

# Create branch at that commit
git branch recovered-branch abc1234

# Or checkout directly
git checkout -b recovered-branch abc1234

Reflog ทำงานอย่างไร?

git reflog เก็บบันทึกการ move ของ HEAD และ branch pointers ไว้ 29 วัน (ค่าเริ่มต้น) ทำให้สามารถกู้คืน commit ที่ยังไม่ถูก garbage collected

7. คำสั่งขั้นสูง (Advanced Commands)

1. git cherry-pick

Apply specific commits

นำ commit ที่เลือกมาتطبيقบน branch ปัจจุบัน (ใช้เมื่อต้องการเอา commit จาก branch อื่นโดยไม่ merge ทั้ง branch)

bash
# Cherry-pick a commit
git cherry-pick abc1234

# Cherry-pick multiple commits
git cherry-pick abc1234 def5678 ghi9012

# Continue after conflict
git cherry-pick --continue

# Abort cherry-pick
git cherry-pick --abort

Use Cases

  • • นำ hotfix จาก release branch ไปใช้ที่ main
  • • Combine features จาก different branches
  • • ย้าย commit ที่ accidentally สร้างบน branch ผิด

2. git bisect

Binary search commits

ใช้ binary search เพื่อค้นหา commit ที่ introduce bug (ประสิทธิภาพสูงมาก!)

bash
# Start bisect
git bisect start

# Mark current commit as bad
git bisect bad

# Mark a good commit (before bug was introduced)
git bisect good v1.0.0

# Git will checkout commits for testing
# Mark each as good/bad until found
git bisect good  # commit is good
git bisect bad   # commit is bad

# Reset after found
git bisect reset

Auto-bisect

# Auto-bisect with script
git bisect start
git bisect bad HEAD
git bisect good v1.0.0
git bisect run ./test-script.sh
git bisect reset

Git will automatically test commits โดยรัน script และกำหนด good/bad อัตโนมัติ

3. Interactive Rebase

Edit commit history

แก้ไข commit history แบบ interactive (squash, reword, reorder, etc.)

bash
# Start interactive rebase
git rebase -i HEAD~3

Interactive Session Example

pick a1b2c3d Add login page
pick d4e5f6g Fix button alignment
pick h7i8j9k Add user profile

# Reorder lines to change commit order
# Change 'pick' to 'r' to reword message
# Change 'pick' to 's' to squash commits

# Save and exit to proceed

4. Submodules

Manage dependencies

จัดการ repository ย่อยภายใน repository หลัก

bash
# Add submodule
git submodule add https://github.com/username/repo.git path/to/submodule

# Update submodule
git submodule update --init --recursive

# Clone with submodules
git clone --recursive https://github.com/username/repo.git

# Remove submodule
git submodule deinit -f path/to/submodule
git rm -f path/to/submodule

ตัวอย่าง

# Add jQuery as submodule
git submodule add https://github.com/jquery/jquery.git vendor/jquery

# Initialize and update
git submodule update --init --recursive

5. Worktrees

Multiple working directories

สร้าง working tree หลายตัวจาก repository เดียวกัน (ทำงานบนหลาย branches พร้อมกัน)

bash
# Create new worktree
git worktree add ../my-feature feature-branch

# List worktrees
git worktree list

# Remove worktree
git worktree remove ../my-feature

# Prune dead worktrees
git worktree prune

Benefits

  • • สวิตช์ branch ได้เร็วขึ้น (ไม่ต้อง stash/checkout)
  • • ทำงานบนหลาย branches พร้อมกัน
  • • ทดสอบ hotfix บน production branch โดยไม่กระทบ development

8. ข้อควรระวัง & เคล็ดลับ (Troubleshooting)

เคล็ดลับที่ควรรู้

git config aliases

git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'

Auto-correct typos

git config --global help.autoCorrect true

Colorize output

git config --global color.ui auto

Default editor

git config --global core.editor code

คำสั่งที่อันตราย

⚠️ อย่าใช้ git push --force

อันตรายมากหาก commit นั้น share กับคนอื่นแล้ว

ใช้ git push --force-with-lease แทน

⚠️ อย่าใช้ git reset --hard

จะลบ working tree และ staging area ทั้งหมด

⚠️ อย่า commit files ที่ sensitive

เช่น .env, private keys, API tokens

ถ้า commit ไปแล้ว ควร rotate keys ทันที!

⚠️ อย่า edit public history

หลัง push แล้ว อย่า rebase/squash commits แล้ว push --force

คำสั่ง Clean Up

git clean

# Remove untracked files
git clean -f

# Remove untracked directories
git clean -fd

# Dry run (show what will be deleted)
git clean -n

# Remove ignored files too
git clean -Xfd

git gc

# Garbage collect
git gc --aggressive

# Prune expired objects
git gc --prune=now

Recovery Checklist

❌ หลังใช้ git push --force

แจ้งทีมทุกคนให้ pull ใหม่ และ อย่า push ระหว่างที่คนอื่น push อยู่

❌ หลัง git reset --hard

ใช้ git reflog เพื่อหา commit ก่อนหน้า

❌ หลังไฟล์ sensitive รั่วไหล

1. Rotate credentials ทันที
2. git filter-branch หรือ BFG to remove
3. ตรวจสอบ git history ว่ามีไฟล์ไหนรั่วอีกไหม

สรุป

Git เป็นเครื่องมือพื้นฐานที่นักพัฒนาและ DevOps ทุกคนต้อง knowledge เพราะเป็น backbone ของการพัฒนาซอฟต์แวร์สมัยใหม่

คู่มือนี้ได้ครอบคลุม command สำคัญตั้งแต่พื้นฐานถึงขั้นสูง พร้อมกับ workflow, best practices และ troubleshooting tips ที่จำเป็นจริงในการทำงาน

🎯

Master the Basics

Start with core commands like git add, commit, push

🚀

Learn Advanced

Understand rebase, reword, cherry-pick for efficiency

🛡️

Follow Best Practices

Commit message conventions, branch naming, PR reviews