Bỏ qua đến nội dung chính
TMT ELECTRONICv2.26.5
DEVELOPMENT TOOLS

Git Commands - Tổng Hợp Lệnh Git Cơ Bản Đến Nâng Cao

20 PHÚT ĐỌCTMT ELECTRONIC TEAM

Hướng dẫn đầy đủ các lệnh Git từ cơ bản đến nâng cao, bao gồm reset, revert, rebase, force push và các thao tác phức tạp khác với ví dụ thực tế.

Git Commands - Tổng Hợp Lệnh Git Cơ Bản Đến Nâng Cao

🔧 Git Commands - Tổng Hợp Lệnh Git Cơ Bản Đến Nâng Cao

Hướng dẫn đầy đủ các lệnh Git từ cơ bản đến nâng cao, bao gồm reset, revert, rebase và các thao tác phức tạp khác.

🚀 Git Cơ Bản

Khởi Tạo Repository

BASH
# Tạo repository mới
git init

# Clone repository từ remote
git clone https://github.com/user/repo.git
git clone https://github.com/user/repo.git my-folder

# Clone với depth (shallow clone)
git clone --depth=1 https://github.com/user/repo.git

# Clone specific branch
git clone -b develop https://github.com/user/repo.git

Cấu Hình Git

BASH
# Cấu hình user toàn cục
git config --global user.name "Your Name"
git config --global user.email "your@email.com"

# Cấu hình cho repository hiện tại
git config user.name "Your Name"
git config user.email "your@email.com"

# Xem cấu hình
git config --list
git config user.name

# Cấu hình editor
git config --global core.editor "code --wait"

# Cấu hình line ending
git config --global core.autocrlf true    # Windows
git config --global core.autocrlf input   # Mac/Linux

📝 Working với Files

Kiểm Tra Trạng Thái

BASH
# Xem trạng thái files
git status
git status -s                             # Short format

# Xem diff
git diff                                  # Working directory vs staging
git diff --staged                         # Staging vs last commit
git diff HEAD                             # Working directory vs last commit
git diff commit1 commit2                  # So sánh 2 commits

# Xem diff của file cụ thể
git diff file.txt
git diff --staged file.txt

Staging & Commit

BASH
# Add files vào staging
git add file.txt                          # Add file cụ thể
git add .                                 # Add tất cả files
git add -A                                # Add tất cả (bao gồm deleted)
git add *.js                              # Add theo pattern

# Add interactive
git add -i                                # Interactive mode
git add -p                                # Patch mode (chọn từng chunk)

# Commit
git commit -m "Commit message"
git commit -am "Message"                  # Add + commit (tracked files)
git commit --amend                        # Sửa commit cuối
git commit --amend -m "New message"       # Sửa message commit cuối

# Commit với template
git commit -t template.txt

# Commit empty (for testing)
git commit --allow-empty -m "Empty commit"

Xóa & Di Chuyển Files

BASH
# Xóa files
git rm file.txt                          # Xóa file khỏi working dir và staging
git rm --cached file.txt                 # Chỉ xóa khỏi staging (keep file)
git rm -f file.txt                       # Force remove

# Di chuyển/đổi tên
git mv old_name.txt new_name.txt

# Unstage files
git reset HEAD file.txt                  # Unstage file cụ thể
git reset HEAD .                         # Unstage tất cả
git restore --staged file.txt            # Git 2.23+

🌿 Branch Management

Tạo & Chuyển Branch

BASH
# Xem branches
git branch                               # Local branches
git branch -r                            # Remote branches  
git branch -a                            # All branches
git branch -v                            # Với commit info

# Tạo branch
git branch feature-branch                # Tạo branch mới
git checkout -b feature-branch           # Tạo và chuyển sang branch
git switch -c feature-branch             # Git 2.23+

# Chuyển branch
git checkout main
git switch main                          # Git 2.23+

# Tạo branch từ commit cụ thể
git checkout -b hotfix abc1234
git branch feature-branch abc1234

# Tạo branch từ remote
git checkout -b local-branch origin/remote-branch
git switch -c local-branch origin/remote-branch

Xóa & Đổi Tên Branch

BASH
# Xóa branch
git branch -d feature-branch             # Safe delete (đã merge)
git branch -D feature-branch             # Force delete
git push origin --delete feature-branch # Xóa remote branch

# Đổi tên branch
git branch -m old-name new-name          # Đổi tên branch khác
git branch -m new-name                   # Đổi tên current branch

# Đổi tên remote branch
git push origin :old-name new-name
git push origin -u new-name

🔄 Merge & Rebase

Merge

BASH
# Merge basic
git merge feature-branch                 # Merge vào current branch
git merge --no-ff feature-branch         # Tạo merge commit

# Merge với strategy
git merge -X theirs feature-branch       # Ưu tiên incoming changes
git merge -X ours feature-branch         # Ưu tiên current branch

# Squash merge
git merge --squash feature-branch        # Merge thành 1 commit

# Abort merge khi conflict
git merge --abort

Rebase

BASH
# Rebase basic
git rebase main                          # Rebase current branch lên main
git rebase main feature-branch           # Rebase feature-branch lên main

# Interactive rebase
git rebase -i HEAD~3                     # Rebase 3 commits cuối
git rebase -i abc1234                    # Rebase từ commit

# Rebase options trong interactive mode:
# pick    = giữ nguyên commit
# reword  = đổi commit message  
# edit    = tạm dừng để edit commit
# squash  = gộp với commit trước
# fixup   = gộp với commit trước (không giữ message)
# drop    = xóa commit

# Continue/abort rebase
git rebase --continue
git rebase --abort
git rebase --skip

⏪ Reset & Revert

Git Reset

BASH
# Reset soft (giữ changes trong staging)
git reset --soft HEAD~1                 # Undo 1 commit
git reset --soft abc1234                # Reset về commit cụ thể

# Reset mixed (default - giữ changes trong working dir)
git reset HEAD~1
git reset abc1234

# Reset hard (xóa tất cả changes)
git reset --hard HEAD~1                 # NGUY HIỂM: mất hết changes
git reset --hard abc1234
git reset --hard origin/main            # Reset về remote state

# Reset file cụ thể
git reset HEAD file.txt                 # Unstage file
git reset abc1234 file.txt              # Reset file về commit cụ thể

Git Revert

BASH
# Revert commit (tạo commit mới đảo ngược)
git revert abc1234                      # Revert 1 commit
git revert HEAD                         # Revert commit cuối
git revert HEAD~2                       # Revert commit cách đây 2

# Revert nhiều commits
git revert abc1234..def5678             # Revert range
git revert --no-commit abc1234..def5678 # Không auto commit

# Revert merge commit
git revert -m 1 abc1234                 # -m 1 = main line parent

🌐 Remote Operations

Remote Management

BASH
# Xem remote
git remote -v                            # Xem remote URLs
git remote show origin                   # Chi tiết remote

# Thêm remote
git remote add origin https://github.com/user/repo.git
git remote add upstream https://github.com/original/repo.git

# Đổi remote URL
git remote set-url origin https://github.com/user/new-repo.git

# Xóa remote
git remote remove origin

Fetch & Pull

BASH
# Fetch (tải về không merge)
git fetch                               # Fetch default remote
git fetch origin                        # Fetch specific remote
git fetch --all                         # Fetch all remotes

# Pull (fetch + merge)
git pull                                # Pull current branch
git pull origin main                    # Pull specific branch
git pull --rebase                       # Pull với rebase thay vì merge

# Pull với strategy
git pull -X theirs                      # Auto resolve conflicts với remote
git pull -X ours                        # Auto resolve conflicts với local

Push

BASH
# Push basic
git push                                # Push current branch
git push origin main                    # Push specific branch
git push -u origin feature-branch       # Push và set upstream

# Force push
git push --force                        # NGUY HIỂM: overwrite remote
git push --force-with-lease             # Safer force push
git push --force-with-lease origin main

# Push tags
git push --tags                         # Push all tags
git push origin v1.0.0                  # Push specific tag

# Push all branches
git push --all origin

🏷️ Tags

Tạo & Quản Lý Tags

BASH
# Lightweight tags
git tag v1.0.0                          # Tạo tag tại HEAD
git tag v1.0.0 abc1234                  # Tạo tag tại commit cụ thể

# Annotated tags (recommended)
git tag -a v1.0.0 -m "Version 1.0.0"
git tag -a v1.0.0 abc1234 -m "Version 1.0.0"

# Xem tags
git tag                                 # List all tags
git tag -l "v1.*"                       # List với pattern
git show v1.0.0                         # Xem chi tiết tag

# Xóa tags
git tag -d v1.0.0                       # Xóa local tag
git push origin --delete v1.0.0        # Xóa remote tag

📚 Log & History

Git Log

BASH
# Log basic
git log                                 # Full log
git log --oneline                       # Compact format
git log --graph                         # Với graph
git log --oneline --graph --all         # Pretty format

# Log với options
git log -5                              # 5 commits cuối
git log --since="2 weeks ago"           # Theo thời gian
git log --until="2024-01-01"
git log --author="John"                 # Theo tác giả

# Log file/directory specific
git log -- file.txt                    # Log của file cụ thể
git log --follow file.txt               # Follow renames

# Log với format
git log --pretty=format:"%h %an %ar %s"
git log --pretty=format:"%C(yellow)%h%Creset %C(blue)%an%Creset %ar %s"

# Log stats
git log --stat                          # Với file changes
git log --shortstat
git log --name-only                     # Chỉ tên files

Tìm Kiếm & Blame

BASH
# Search trong commits
git log --grep="bug fix"                # Tìm trong commit messages
git log -S "function_name"              # Tìm code changes
git log -G "regex_pattern"              # Tìm với regex

# Blame
git blame file.txt                      # Xem ai viết từng dòng
git blame -L 10,20 file.txt             # Chỉ dòng 10-20
git blame -C file.txt                   # Detect moved/copied lines

# Find commit that introduced bug
git bisect start
git bisect bad                          # Current commit is bad
git bisect good abc1234                 # Known good commit
# Git sẽ hướng dẫn test từng commit
git bisect reset                        # Kết thúc bisect

🔍 Stash

Working với Stash

BASH
# Stash basic
git stash                               # Stash changes
git stash push -m "WIP: feature"       # Stash với message
git stash -u                            # Include untracked files
git stash -a                            # Include all files

# Xem stashes
git stash list                          # List all stashes
git stash show                          # Show latest stash
git stash show stash@{1}                # Show specific stash
git stash show -p                       # Show with diff

# Apply stash
git stash apply                         # Apply latest stash
git stash apply stash@{1}               # Apply specific stash
git stash pop                           # Apply và xóa stash

# Quản lý stashes
git stash drop                          # Xóa latest stash
git stash drop stash@{1}                # Xóa specific stash
git stash clear                         # Xóa all stashes

# Stash branches
git stash branch feature-branch         # Tạo branch từ stash

🧹 Cleanup Commands

Clean Working Directory

BASH
# Clean untracked files
git clean -n                            # Dry run (xem sẽ xóa gì)
git clean -f                            # Force clean files
git clean -fd                           # Clean files và directories
git clean -fX                           # Clean ignored files only
git clean -fx                           # Clean tất cả untracked

# Interactive clean
git clean -i                            # Interactive mode

Prune & Garbage Collection

BASH
# Remote cleanup
git remote prune origin                 # Xóa stale remote branches
git fetch --prune                       # Fetch và prune

# Local cleanup
git gc                                  # Garbage collection
git gc --aggressive                     # Aggressive cleanup
git prune                               # Remove unreachable objects

# Branch cleanup
git branch --merged | grep -v main | xargs git branch -d  # Xóa merged branches

🔧 Advanced Commands

Cherry Pick

BASH
# Cherry pick commit
git cherry-pick abc1234                # Apply commit to current branch
git cherry-pick abc1234..def5678       # Cherry pick range
git cherry-pick --no-commit abc1234    # Apply without committing

# Cherry pick options
git cherry-pick --continue             # Continue after resolving conflicts
git cherry-pick --abort                # Abort cherry pick
git cherry-pick -x abc1234             # Add reference to original commit

Reflog

BASH
# Xem reflog
git reflog                             # Local repo history
git reflog show HEAD                   # HEAD movements
git reflog show branch-name            # Branch reflog

# Recover lost commits
git reflog                             # Find lost commit
git checkout abc1234                   # Go to lost commit
git branch recovered-branch            # Create branch to save it

# Reflog cleanup
git reflog expire --expire=90.days.ago --all
git reflog delete HEAD@{2}

Archive & Bundle

BASH
# Create archive
git archive --format=zip HEAD > project.zip
git archive --format=tar.gz HEAD > project.tar.gz
git archive --format=zip abc1234 > version.zip

# Bundle repository
git bundle create repo.bundle HEAD main
git bundle create repo.bundle abc1234..def5678

# Clone from bundle
git clone repo.bundle repo-copy

🚨 Emergency Commands

Khôi Phục Khi Gặp Vấn Đề

BASH
# Undo last commit (keep changes)
git reset --soft HEAD~1

# Undo last commit (lose changes)
git reset --hard HEAD~1

# Undo multiple commits
git reset --hard HEAD~3

# Khôi phục file từ commit cụ thể
git checkout abc1234 -- file.txt
git restore --source=abc1234 file.txt

# Khôi phục toàn bộ working directory
git reset --hard HEAD
git checkout .

# Khôi phục từ remote
git reset --hard origin/main
git clean -fd

# Tìm và khôi phục lost commit
git reflog
git branch recovery abc1234

Xử Lý Conflicts

BASH
# Khi có conflict trong merge
git status                             # Xem conflicted files
# Edit files để resolve conflicts
git add .                              # Mark resolved
git commit                             # Complete merge

# Khi có conflict trong rebase
git status                             # Xem conflicted files  
# Edit files để resolve conflicts
git add .                              # Mark resolved
git rebase --continue                  # Continue rebase

# Abort operations
git merge --abort                      # Cancel merge
git rebase --abort                     # Cancel rebase
git cherry-pick --abort                # Cancel cherry-pick

# Use merge tools
git mergetool                          # Launch merge tool
git config --global merge.tool vimdiff # Set default tool

📋 Git Aliases

Useful Aliases

BASH
# Setup common aliases
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit

# Advanced aliases
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
git config --global alias.graph 'log --oneline --graph --all'
git config --global alias.amend 'commit --amend --no-edit'

# Shortcut for common operations
git config --global alias.pushf 'push --force-with-lease'
git config --global alias.undo 'reset --soft HEAD~1'
git config --global alias.wip 'commit -am "WIP"'

💡 Best Practices

Commit Messages

BASH
# Good commit message format:
# <type>(<scope>): <description>
#
# [optional body]
#
# [optional footer]

# Examples:
feat(auth): add user login functionality
fix(api): resolve null pointer exception in user service
docs(readme): update installation instructions
style(css): fix button alignment on mobile
refactor(utils): extract validation logic to separate module
test(unit): add tests for user authentication
chore(deps): update dependencies to latest versions

Workflow Tips

BASH
# Before starting work
git pull --rebase                      # Get latest changes

# Daily workflow
git add .
git commit -m "feat: implement feature X"
git push

# Before merging feature branch
git checkout main
git pull
git checkout feature-branch
git rebase main                        # Clean up history
git checkout main
git merge --no-ff feature-branch       # Create merge commit

# Code review workflow
git push -u origin feature-branch      # Push feature branch
# Create pull request
# After review, squash and merge

Safety Tips

BASH
# Always backup before risky operations
git branch backup-$(date +%Y%m%d-%H%M%S)

# Use --force-with-lease instead of --force
git push --force-with-lease

# Check what will be deleted before cleaning
git clean -n

# Use interactive mode for complex operations
git rebase -i
git add -p

# Verify state before pushing
git log --oneline -5
git status

🎯 Kết Luận

Git là công cụ mạnh mẽ với rất nhiều lệnh và options. Key points:

Cơ bản hàng ngày:

  • git add, git commit, git push, git pull
  • git status, git log, git diff
  • git branch, git checkout, git merge

Nâng cao:

  • git rebase, git reset, git revert
  • git stash, git cherry-pick, git reflog
  • Force push với --force-with-lease

Emergency:

  • git reflog để tìm lost commits
  • git reset --hard để khôi phục working dir
  • git clean -fd để xóa untracked files

Remember: Luôn backup trước khi thực hiện operations nguy hiểm!

THẺ

  • #Git
  • #Version Control
  • #Git Commands
  • #Git Reset
  • #Git Rebase
  • #Git Merge
  • #Force Push
  • #Git Stash
  • #Git Reflog
  • #Development Tools
  • #Source Control
  • #Best Practices
Xem tất cả bài viết →
Hợp tác